JS中的箭头函数表达式

版权声明:wuyujin1997 reserve all rights. https://blog.csdn.net/wuyujin1997/article/details/88829555

intro

函数表达式是一个匿名函数,其可以作为一个表达式,赋值(其地址)到一个变量,然后用这个变量名去调用这个匿名函数。
ES6中新增了箭头函数表达式。

语法

箭头函数表达式:(x, y) => x - y;
相当于匿名函数:

function(x, y) {
    return x - y;
}

他们都可以(将地址)赋值给变量,然后使用变量去多次调用。

  • 包围参数列表的小括号()
    无参(一定要写括号):() => {...}
    1个参数(括号可省略):x => {...}
    多个参数(一定要写括号):(x, y) => {}
  • 包围函数体的大括号{}
    • 如果只有返回语句,可以省略{}return关键字,直接写返回值。
      但如果返回值是object类型,应该用()包围对象。
      num => ({age:num})。否则返回值为undefined
      原因见JS中的{},()及自调用
    • 如果有多条语句,函数体用{}括起来,不可省略。

箭头函数表达式的this

之前的匿名函数中嵌套方法的this指向不一定。
但在ES6新增的特性匿名函数中,this是词法作用域,由上下文确定。

普通的匿名函数:

obj = {
  birth: 1990,
  getAge: function() {
    console.log("getAge()中的this.birth:", this.birth);
    fn = function() {
      return this.birth;	// undefined, 这里的this指向window。
    };
    return fn();
  }
};
{birth: 1990, getAge: ƒ}

console.log(obj.getAge())
getAge()中的this.birth: 1990
undefined

// getAge()中的this.birth为1990.
// getAge()中嵌套的fn()中的this.birth为undefined,因为那个this指向window。

ES6新增的箭头函数:

obj = {
  birth: 1990,
  getAge: function() {
    console.log("getAge()中的this.birth:", this.birth);
    fn = () => this.birth;
    console.log("用func.apply()替换this的结果:", fn.apply({birth: 2000}));
    return fn();
  }
};

console.log(obj.getAge());
// getAge()中的this.birth: 1990
// 用func.apply()替换this的结果: 1990
// 1990

由于箭头函数表达式中的this是词法作用域,指向由上下文决定。
所以使用func.appy(), call(), bind()去指向thisArg对箭头函数是无效的。
ES6中箭头函数表达式中的this指向问题

猜你喜欢

转载自blog.csdn.net/wuyujin1997/article/details/88829555