javascript - 为什么括号会导致对象变得未绑定?
问题描述
当我用括号包围一个新的对象调用并立即在其上调用一个方法时,Node(或通常只是 v8)将抛出“TypeError:this.getName is not a function”错误。如果我不将其包装在括号中,则不会抛出任何错误并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'未绑定?
解决方案
您依赖于自动分号插入,但它没有按您期望的方式工作。
这个:
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();
推荐阅读
- openshift - 如何在 Openshift 中使用 oc cli 删除文件/目录
- python - 一个简单的计算器。我想在用户输入 1-4 以外的数字后显示错误消息。它在一个while循环中
- r - R:递归评估存储为列表的二叉树
- python - 如何处理“ValueError:使用序列设置数组元素”。错误
- c# - 如何在 ASP NET Core 中使用 DI 注入特定的接口实现
- javascript - 有没有办法将 PoseNet 与实时网络摄像头提要一起使用?
- sql-server - 如何使用 T-SQL 触发器在两个表中插入同一行?
- c# - 如何在 30 秒内使用 smtp 忽略相同的电子邮件?
- r - 在 R 中创建月平均值列
- angular - Angular 9 - 如何通过模拟路由器来测试调用 navigateByUrl 的服务