Javascript 为什么圆括号会导致对象解除绑定?
当我用parens包围一个新的对象调用并立即对其调用一个方法时,Node(或者通常是v8)将抛出一个“TypeError:this.getName不是函数”错误。如果我不将其包装在parens no中,那么不会抛出错误,并且Javascript 为什么圆括号会导致对象解除绑定?,javascript,node.js,v8,Javascript,Node.js,V8,当我用parens包围一个新的对象调用并立即对其调用一个方法时,Node(或者通常是v8)将抛出一个“TypeError:this.getName不是函数”错误。如果我不将其包装在parens no中,那么不会抛出错误,并且此已正确绑定 function Greeter(name) { this.name = name; } Greeter.prototype.getName = function() { return this.name; } Greeter.prototype.h
此
已正确绑定
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”没有绑定 您依赖于自动分号插入,但它没有按您预期的方式工作 这: 相当于:
let mygreeter = new Greeter('Olive');
let result_of_call = (function() {
console.log(`Hello ${this.getName()}`);
}(mygreeter));
Greeter.prototype.helloWorld = result_of_call.helloWorld();
您需要在上一个表达式后面加一个分号,以防止将(…)
解释为“将此函数作为带参数的IIFE调用”
我觉得这以前是有用的。。。。我没有看到什么明显的东西吗?你依靠(ASI)自动插入分号来解释你的实际意思。它看到一个函数表达式后跟
(…)
,因此它在设置步骤调用你的函数什么是JavaScript向导。哦,这就是当我在关闭linter的情况下启动一个项目时发生的情况。这太棒了,我用JavaScript编程多年,我花了一些时间来理解这个问题和你的答案。现在看起来很明显,如果我们不依赖分号,那么代码就好像在一行上,这就是一种生活。只是一个问题,为什么我们不在函数周围加上括号呢?@CristianTraìna-位于=
的右侧将其置于表达式上下文中。@Quentin我刚刚做了一些测试,我发现等号也有魔力。你从哪里学到的表达语境?
let mygreeter = new Greeter('Olive');
let result_of_call = (function() {
console.log(`Hello ${this.getName()}`);
}(mygreeter));
Greeter.prototype.helloWorld = result_of_call.helloWorld();
Greeter.prototype.helloWorld = function() {
console.log(`Hello ${this.getName()}`);
};
(new Greeter('Olive')).helloWorld();