简体   繁体   English

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

[英]Why do parentheses cause object to become unbound?

When I surround a new object invocation with parens and call a method on it immediately Node (or just v8 in general) will throw a "TypeError: this.getName is not a function" error. 当我用括号包围一个新的对象调用并立即对其调用一个方法时,Node(或一般来说只是v8)将引发“ TypeError:this.getName不是函数”错误。 If I don't wrap it in parens no then no error will get thrown and this is properly bound. 如果我没有在括号包裹它没有那么没有错误会得到抛出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();

What do the parens get interpreted as here, and why is 'helloWorld' unbound? 括号被解释为什么?为什么“ helloWorld”不受约束?

You are depending on automatic semi-colon insertion and it isn't working the way you expect. 您依靠自动分号插入,并且无法按预期方式工作。

This: 这个:

 Greeter.prototype.helloWorld = function() { console.log(`Hello ${this.getName()}`); } // Throws, this in any class methods are bound to the global (new Greeter('Olive')).helloWorld(); 

is equivalent to: 等效于:

let mygreeter = new Greeter('Olive');

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

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

You need to put a semi-colon after the previous expression to prevent the (...) being interpreted as "Call this function as an IIFE with arguments" 您需要在前一个表达式之后加上分号,以防止将(...)解释为“将此函数作为带有参数的IIFE调用”

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM