Search code examples
javascriptnode.jsoopprototypejs

Setting member variables of Prototype class in Nodejs


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

The code above always overwrites the private variables initialized in other instances. It displays 2, 2, 2 instead of 0, 1, 2. Are the member variables m set appropriately this way?

Yet it works fine without process.nextTick. Any idea?


Solution

  • Your code example is incomplete, however I believe your real code still suffers the following issue:

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

    Change your code to:

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

    bind is used to ensure that the this value inside the nextTick callback is the current MyClass instance.