对一个函数表达式来说,this 会随着函数调用时的上下文改变。而箭头函数,this 会基于词法作用域。箭头函数遵循普通变量的寻找方式,先在当前作用域中查找 this ,若没有找到则会继续寻找上一层作用域。
直接调用
1 2 3 4 5
constfoo = () => { returnthis; }
console.log(foo()); // window or global object
完全与函数表达式相同。
作为构造函数
1 2 3 4 5 6 7 8 9 10 11
constOrder = (main, side, dessert) => { this.main = main; this.side = side; this.dessert = dessert; this.order = function () { return`I will have ${this.main} with ${this.side} and finish off with a ${this.dessert}`; } } const newOrder = newOrder("sushi", "soup", "yogurt"); // Order is not a constructor
functionOrder(main, side, dessert) { this.main = main; this.side = side; this.dessert = dessert; this.order = () => { return`I will have ${ this.main } with ${ this.side } and finish off with a ${ this.dessert } `; } } const newOrder = newOrder("sushi", "soup", "yogurt");
console.log(newOrder.order()); // I will have sushi with soup and finish off with a yogurt
作为对象方法调用
1 2 3 4 5 6 7 8 9 10 11
const myObject = { main: "butter chicken", side: "rice", dessert: "ice cream", order: () => { return`I will have ${this.main} with ${this.side} and finish off with ${this.dessert}`; } }
console.log(myObject.order()); // I will have undefined with undefined and finish off with undefined
与函数表达式表现的不同, 作为对象方法时箭头函数不能直接替换函数表达式。
在严格模式下使用
1 2 3 4 5 6 7
"use strict"; constfoo = () => { returnthis; };
console.log(foo() === undefined); // false console.log(foo()); // window or global object