ES6 Arrow function: why “this” points differently when used in constructor and object literal?
我知道箭头函数从封闭范围继承了
考虑以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | function Obj() { this.show = () => { console.log(this); }; } const o = new Obj(); const o2 = { show: () => { console.log(this); } } o.show(); // o o2.show() // window || undefinded |
1 2 3 4 5 6 7 | function Obj() { this.show = () => { console.log(this); }; } const o = new Obj(); o.show(); |
此处" this"基于关键字" new"的规则,它指向具有在Obj()内部定义的结构的新对象(新对象是上下文)。
有关更多信息,请访问:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
1 2 3 4 5 6 | const o2 = { show: () => { console.log(this); } } o2.show() // window || undefinded |
此处的" this "在运行时获取其值,并且由于lambda函数和对象文字均未定义上下文,因此剩下的上下文是全局上下文,这就是为什么要获得该值的原因。
那是因为在声明时
1 2 3 4 5 6 | // IIFE const x = (() => ({a: 1, b: 2, sum() {return this.a + this.b}}))(); console.log(`x.sum() => ${x.sum()}`); // Object.create const y = Object.create({a:1, b:2, sum() {return this.a + this.b}}); console.log(`y.sum() => ${y.sum()}`); |
好吧,找到答案了,如" javascript忍者的秘密"中所述:
Arrow functions don't have their
own context. Instead, the context is inherited
from the function in which they’re defined.
因此在构造函数
同时,在定义对象常量时,