es6函数的扩展

来源:互联网 发布:软件外包服务提供商 编辑:程序博客网 时间:2024/04/28 18:38

摘自函数的扩展

1.rest参数

ES6引入rest参数(形式为“…变量名”),用于获取函数的多余参数,这样就不需要使用arguments对象了。
arguments对象并没有数组的方法,rest参数搭配的变量是一个数组。

function add(...values){  let sum = 0;  for(let val of values){    sum += val;  }  return sum;}add(3, 4, 5);

rest参数中的变量代表一个数组,所以数组特有的方法都可以用于这个变量。

const push = (array, ...items) => {  items.forEach((item) => {    array.push(item);  });}const arr = [];push(arr, 1, 2, 3);

扩展运算符

扩展运算符(spread)是三个点(…)。它好比rest参数的逆运算,将一个数组转为用逗号分隔的参数序列。

console.log(1, ...[2, 3, 4], 5)//1 2 3 4 5

该运算符主要用于函数调用。

function push(array, ...items) {  array.push(...items);}const arr = [];const numbers = [3,4,5,6,7];push(arr, ...numbers);

2.箭头函数

ES6允许使用=>定义函数。

const foo = val => val;const foo = function(val){  return val;}#如果箭头函数不需要参数或需要多个参数,就使用一个圆括号代表参数部分。const sum = (num1, num2) => num1 + num2;// 等同于const sum = function(num1, num2) {  return num1 + num2;};#如果箭头函数的代码块部分多于一条语句,就要使用大括号将它们括起来,并且使用return语句返回。var getTempItem = id => ({ id: id, name: "Temp" });#箭头函数的一个用处是简化回调函数。// 正常函数写法var result = [6,1,8].sort(function(a, b) {  return a - b;});// 箭头函数写法var result = [6,1,8].sort((a, b) => a - b);

箭头函数有几个使用注意点。

  • 1.函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
  • 2.不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误。
  • 3.不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用Rest参数代替。
  • 4.不可以使用yield命令,因此箭头函数不能用作Generator函数。

上面四点中,第一点尤其值得注意。this对象的指向是可变的,但是在箭头函数中,它是固定的。

function Timer () {  this.seconds = 0  setInterval(() => this.seconds++, 1000)}var timer = new Timer()setTimeout(() => console.log(timer.seconds), 3100)

除了this,以下三个变量在箭头函数之中也是不存在的,指向外层函数的对应变量:arguments、super、new.target

function foo() {   setTimeout( () => {      console.log("args:", arguments);   },100);}foo( 2, 4, 6, 8 );// args: [2, 4, 6, 8]

上面代码中,箭头函数内部的变量arguments,其实是函数fooarguments变量。

0 0