javascript 高级编程系列 - 箭头函数

发布时间 2023-03-23 11:48:19作者: 箫笛

箭头函数是一种使用用箭头(=>)定义函数的新语法,它不同于传统的javascript函数。

  • 没有this, super, arguments 和 new.target绑定: 箭头函数中的this, super, arguments, 及new.target
    这些值由外围最近一层非箭头函数决定。
  • 不能通过new关键字调用: 箭头函数没有[[Construct]] 方法,所以不能被用作构造函数,如果通过new关键字
    调用箭头函数,程序会抛出错误。
  • 没有原型: 由于不可以通过new关键字调用箭头函数,因而没有构建原型的需求,所以箭头函数不存在
    prototype这个属性。
  • 不可以改变this绑定:函数内部的this值不可被改变,在函数的生命周期内始终保持一致。
  • 不支持arguments对象:箭头函数没有arguments绑定,所以你必须通过命名参数和不定参数这两种形式访问
    函数的参数。
  • 不支持重复的命名参数:无论严格模式还是非严格模式下,箭头函数都不支持重复的命名参数。

1. 箭头函数语法

箭头函数只有一个参数

// 箭头函数
let reflect = value => value;
// 普通函数
let reflect = function(value) {
  return value;
};

箭头函数有多个参数

// 箭头函数
let sum = (num1, num2) => num1 + num2;
// 普通函数
let sum = function(num1, num2) {
  return num1 + num2;
}

箭头函数没有参数

// 箭头函数
let getName = () => 'Nicholas';
// 普通函数
let getName = function() {
  return 'Nicholas';
};

箭头函数用花括号包裹函数体

// 箭头函数
let sum = (num1, num2) => {
  return num1 + num2;
};
// 普通函数
let sum = function (num1, num2) {
  return num1 + num2;
};

创建空函数

// 箭头函数
let doNothing = () => {};
// 普通函数
let doNothing = function(){};

箭头函数返回对象字面量

// 箭头函数
let getTempItem = id => ({id: id, name: 'Temp'});
// 普通函数
let getTempItem = function(id) {
  return {
    id: id,
    name: 'Temp'
  };
};

2. 创建立即执行函数表达式

// 普通函数
let person = function(name) {
  return {
    getName: function() {
      return name;
    }
  };
}('Nicholas');
console.log(person.getName()); // 'Nicholas'

// 箭头函数
let person = ((name) => {
  return {
    getName: function(){
      return name;
    }
  };
})('Nicholas');

3. 箭头函数没有this绑定

箭头函数中没有this 绑定,必须通过查找作用域链来决定其值。如果箭头函数被非箭头函数包含,则this绑定
的是最近一层非箭头函数的this;否则,this的值会被设置为全局对象。

// 普通函数
let PageHandler = {
  id: '123456',
  init: function(){
    document.addEventListener('click', function(event){
      // 此处this引用的是document,而非PageHandler
      this.doSomething(event.type); // 抛出错误
    }, false);
  },
  doSomething: function(type){
    console.log('Handling' + type + ' for' + this.id);
  }
};

// 箭头函数
let PageHandler = {
  id: '123456',
  init: function(){
    document.addEventListener('click', event => this.doSomething(event.type), false);
  },
  doSomething: function(type){
    console.log('Handling' + type + ' for' + this.id);
  }
};

4. 箭头函数和数组

// 普通函数
const result = values.sort(function(a, b){
  return a - b;
}); 
// 箭头函数
const result = values.sort((a, b) => a -b );

5. 箭头函数没有arguments绑定

箭头函数没有自己的arguments对象,且未来无论函数在哪个上下文中执行,箭头函数始终可以访问外围函数的
arguments对象。

function createArrowFunction(){
  return () => arguments[0];
}
const arrowFunc = createArrowFunction(5);
console.log(arrowFunc()); // 5

6. 箭头函数的辨识

const comparator = (a, b) => a - b;
console.log( typeof comparator); // 'function'
console.log( comparator instanceof Function); // true

7. 箭头函数与call 和 apply方法

箭头函数中的this的值,不会随着call 和 apply 方法的上下文而变化

const sum = (num1, num2) => num1 + num2;
console.log(sum.call(null, 1, 2)); // 3
console.log(sum.apply(null, [1, 2])); // 3