为什么括号会导致对象变得未绑定? [英] Why do parentheses cause object to become unbound?
问题描述
当我用括号包围一个新的对象调用并立即对其调用一个方法时,Node(或一般来说只是v8)将引发"TypeError:this.getName不是函数"错误.如果我不将其包装在括号中,则不会抛出任何错误,并且 this
已正确绑定.
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. If I don't wrap it in parens no then no error will get thrown and this
is properly bound.
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();
parren的解释是什么,为什么'helloWorld'没有绑定?
What do the parens get interpreted as here, and why is 'helloWorld' unbound?
推荐答案
您所依赖的是自动分号插入,它无法按您期望的方式工作.
You are depending on automatic semi-colon insertion and it isn't working the way you expect.
此:
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();
您需要在前一个表达式后加上分号,以防止(...)
解释为将此函数作为带有参数的IIFE调用"
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"
Greeter.prototype.helloWorld = function() {
console.log(`Hello ${this.getName()}`);
};
(new Greeter('Olive')).helloWorld();
这篇关于为什么括号会导致对象变得未绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!