Javascript Arrow Function This
箭头函数不同于传统 JavaScript 中的函数,箭头函数并没有属于⾃⼰的 this,它所谓的 this 是捕获其所在上下⽂的 this 值,作为⾃⼰的 this 值。箭头函数中 this 的指向在它在定义时已经确定了,之后不会改变。
參考下面的例子:对象 obj 的方法 b 是使用箭头函数定义的,这个函数中的 this 就永远指向它定义时所处的全局执行环境中的 this,即便这个函数是作为对象 obj 的方法调用,this 依旧指向 Window 对象。
var id = "GLOBAL";
var obj = {
id: "OBJ",
a: function () {
console.log(this.id);
},
b: () => {
console.log(this.id);
},
};
obj.a(); // browser & node: 'OBJ'
obj.b(); // browser: 'GLOBAL'; node: undefined需要注意,定义对象的大括号{}是无法形成一个单独的执行环境的,它依旧是处于全局执行环境中。參考下面例子,無論是有多少層,arrow function 都不會有自己的 this。
var id = "GLOBAL";
var obj = {
id: "OBJ",
c: {
id: "C",
d: () => {
console.log(this.id);
},
},
};
obj.c.d(); // browser: 'GLOBAL'; node: undefined
但是一旦涉及 normal function,就會形成一個新的 context,比如在下面例子中的,e() 會形成一個新的 context,導致 this 指向了 “OBJ”,所以 arrow function 的 this 也指向 “OBJ”。
var id = "GLOBAL";
var obj = {
id: "OBJ",
e: function () {
return {
id: "E",
f: () => {
console.log(this.id);
},
};
},
};
obj.e().f(); // 'OBJ'