ES6 箭头函数:为什么 "this" 在构造函数和对象字面量中使用时指向不同?

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

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

function Obj() {
  this.show = () => {
    console.log(this);
  };
}
const o = new Obj();
const o2 = {
  show: () => {
    console.log(this);
  }
}

o.show(); // o
o2.show() // window || undefinded

好的,找到答案,如"Secrets of the javascript ninja"中所述:

Arrow functions don't have their own context. Instead, the context is inherited from the function in which they’re defined.

所以在构造函数中 this === {}。 而在定义对象字面量时,this 仍然指向全局对象,如果在严格模式下,则指向 undefined

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

// 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()}`);

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

const o2 = {
  show: () => {
    console.log(this);
  }
}
o2.show() // window || undefinded

这里 "this" 在运行时获取它的值,因为 lambda 函数和对象文字都没有定义上下文,剩下的上下文是全局上下文,这就是你获取该值的原因。