关于javascript:ES6箭头函数:为什么在构造函数和对象文字中使用” this”时指向不同?

ES6 Arrow function: why “this” points differently when used in constructor and object literal?

我知道箭头函数从封闭范围继承了this。但是,仍然无法理解为什么在对象常量中定义的箭头函数中的this指向全局对象,而在构造函数中则指向创建的对象。
考虑以下代码:

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函数和对象文字均未定义上下文,因此剩下的上下文是全局上下文,这就是为什么要获得该值的原因。


那是因为在声明时Object尚未初始化。您可以使用立即调用的函数表达式(IIFFE)强制使用初始化,也可以使用Object.create。类似于:

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.

因此在构造函数this === {}中。
同时,在定义对象常量时,this仍指向全局对象,或者在严格模式下仍指向undefined