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

Par*_*ris 3 javascript v8 node.js

当我用parens包围一个新的对象调用并在其上调用一个方法时,Node(或者通常只是v8)会抛出一个"TypeError:this.getName不是函数"错误.如果我不将它包装在parens中,那么不会抛出任何错误并且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();
Run Code Online (Sandbox Code Playgroud)

这些parens在这里被解释为什么,为什么'helloWorld'不受约束?

Que*_*tin 9

您依赖于自动分号插入,它不能按预期的方式工作.

这个:

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

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

相当于:

let mygreeter = new Greeter('Olive');

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

Greeter.prototype.helloWorld = result_of_call.helloWorld();
Run Code Online (Sandbox Code Playgroud)

您需要在前一个表达式之后放置一个分号,以防止(...)被解释为"将此函数称为带参数的IIFE"

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

(new Greeter('Olive')).helloWorld();
Run Code Online (Sandbox Code Playgroud)