构造函数中的箭头函数和 this

Arrow function and this inside a constructor function

我读过这段关于 this 关键字的内容:https://bonsaiden.github.io/JavaScript-Garden/#function.this

在第一种情况下 this 指的是 global objet,这看起来很正常,因为当我们有一个箭头函数时,它会自动将 this 与外部的对象绑定范围。

var obj = {
      foo : () => console.log(this)
    }
console.log(obj);
obj.foo()

但是,我无法解释以下行为:

function bar(){
  this.foo = () => console.log(this)
} 

var obj = new bar()
console.log(obj);
obj.foo()

现在,this 指的是 obj 而不是 global。这是为什么 ?在我看来,将 new 关键字与构造函数一起使用应该 return 一个对象 obj 与第一个示例中的对象完全相同。所以箭头函数应该有一个 this,它指的是 global 而不是 obj。你能给我解释一下第二种情况吗?

尽管我自己对对象的处理能力还很差(需要在这方面努力),但我认为当您执行 const test = new Test() 时,您会 初始化 一个新对象。这样, this 的范围(?)仅引用新创建的对象,因此你为什么要这样做 this.foo 然后你通过使用 [=13= 引用那个 foo 属性 ].另一方面,当你只是做 const obj = { .... } 时,你实际上并没有初始化一个新对象,所以 this 直接进入全局对象 - window。因此,const test = new Test 创建了一个 new 对象,而仅使用 const obj = {} 而不是 新对象并且 this 默认转到 window 对象。

函数->No separate this

Until arrow functions, every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming

Read more about the new keyword here

The constructor function ... is called with the specified arguments, and with this bound to the newly created object.

bar() 构造函数将 this 定义为自身。