在 Nodejs 中设置 Prototype 类的成员变量

Setting member variables of Prototype class in Nodejs

本文关键字:成员 变量 Prototype Nodejs 设置      更新时间:2023-09-26
var MyClass = (function() {    
  function MyClass(m) {
    this.m = m;
  }
  MyClass.prototype.temp = function() {
    process.nextTick(function() {
      console.log(m);
    });
  }
});
for (var i=0; i<3; i++) {
  var t = new MyClass(i);
}

上面的代码总是覆盖在其他实例中初始化的私有变量。它显示 2、2、2 而不是 0、1、2。成员变量m以这种方式正确设置吗?

然而,它在没有process.nextTick的情况下工作正常。知道吗?

您的代码示例不完整,但是我相信您的真实代码仍然存在以下问题:

process.nextTick(function() {
    console.log(m); //where does the m variable came from?
});

将代码更改为:

process.nextTick((function() {
    console.log(this.m);
}).bind(this));

bind用于确保nextTick回调中的this值是当前MyClass实例。