当我用括号包围一个新对象调用并立即调用它的方法时,Node(或者一般来说只是 v8)将抛出“TypeError:this.getName 不是函数”错误。如果我不将它包裹在括号中,则不会抛出任何错误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”未绑定?
您依赖于自动分号插入,但它没有按您期望的方式工作。
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();
相当于:
let mygreeter = new Greeter('Olive');
let result_of_call = (function() {
console.log(`Hello ${this.getName()}`);
}(mygreeter));
Greeter.prototype.helloWorld = result_of_call.helloWorld();
您需要在前一个表达式后面添加分号,以防止出现(...)
被解释为“将此函数作为带参数的 IIFE 调用”
Greeter.prototype.helloWorld = function() {
console.log(`Hello ${this.getName()}`);
};
(new Greeter('Olive')).helloWorld();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)