javascript - 为什么括号会导致对象成为未绑定(bind)的?

标签 javascript node.js v8

当我用括号包围一个新的对象调用并立即在其上调用一个方法时,Node(或通常只是 v8)将抛出“TypeError:this.getName 不是函数”错误。如果我不将它包装在括号 no 中,则不会抛出任何错误,并且 this 已正确绑定(bind)。

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();

parens 在这里被解释成什么,为什么 'helloWorld' 是未绑定(bind)的?

最佳答案

您依赖于自动分号插入,但它没有按您预期的方式工作。

这个:

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();

你需要在前面的表达式后面放一个分号,以防止 (...) 被解释为“Call this function as an IIFE with arguments”

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

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

关于javascript - 为什么括号会导致对象成为未绑定(bind)的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50029140/

相关文章:

javascript - Ext.NET 中的复选框问题

javascript - 在 angular.js 中创建级联保管箱

java - 在javascript中调用的Struts2 Action 无法获取 session 对象

javascript - NodeJS 和 Cradle 未连接

javascript - 如何使用 jwt 解码 token

node.js - 跟踪 Node.js 中的内存泄漏 - v8 分析器与 htop

node.js - 如何在 V8 中取消缓存 error.stack?

javascript - 为什么 Express 句柄不抛出新错误?

javascript - 期望不正确的智能感知方法

Node.js 分析 : high usage in "(program)" section