为什么括号会导致对象成为未绑定的?

Why do parentheses cause object to become unbound?

当我用括号括起一个新对象调用并立即对其调用方法时,Node(或通常只是 v8)将抛出 "TypeError: this.getName is not a function" 错误。如果我不将其包装在括号中,则不会抛出任何错误并且 this 已正确绑定。

function Greeter(name) {
  this.name = name;
}

Greeter.prototype.getName = function() {
  return this.name;
}

Greeter.prototype.helloWorld = function() {
  console.log(`Hello ${this.getName()}`);
}

// Throws, this in any class methods are bound to the global
(new Greeter('Olive')).helloWorld();
// Doesn't throw, this is bound to the object as expected
new Greeter('Olive').helloWorld();

这里的括号是什么意思,为什么 'helloWorld' 是未绑定的?

您依赖于自动分号插入,但它没有按您预期的方式工作。

这个:

Greeter.prototype.helloWorld = function() {
  console.log(`Hello ${this.getName()}`);
}

// Throws, this in any class methods are bound to the global
(new Greeter('Olive')).helloWorld();

相当于:

let mygreeter = new Greeter('Olive');

let result_of_call = (function() {
  console.log(`Hello ${this.getName()}`);
}(mygreeter));

Greeter.prototype.helloWorld = result_of_call.helloWorld();

您需要在前面的表达式后加一个分号,以防止 (...) 被解释为 "Call this function as an IIFE with arguments"

Greeter.prototype.helloWorld = function() {
  console.log(`Hello ${this.getName()}`);
};

(new Greeter('Olive')).helloWorld();