内部函数调用无法访问JavaScript(node.js)变量。 now.js

时间:2011-07-23 15:56:44

标签: javascript node.js mongoose nowjs-sockets

我在一个节点项目中使用now.js和Mongoose,但是在访问mongoose函数中的this.now对象时遇到了问题。 E.g。

everyone.now.joinDoc = function (project_id){  
  this.now.talk(); //this will work
  Project.findOne({'_id':project_id}, function(err, project){
    if(project){
      this.now.talk(); // this will not work "TypeError: Cannot call method 'bark' of undefined"
    };
  });
};

2 个答案:

答案 0 :(得分:4)

将代码更改为:

everyone.now.joinDoc = function (project_id){  
  this.now.talk();  // this will work
  var that = this;  // save 'this' to something else so it will be available when 'this' has been changed
  Project.findOne({'_id':project_id}, function(err, project){
    if(project){
      that.now.talk();  // use local variable 'that' which hasn't been changed
    };
  });
};

在你的内部函数中,this可能被设置为其他东西。因此,要保留要访问的值,请将其分配给内部函数中可用的其他局部变量。

答案 1 :(得分:1)

everyone.now.joinDoc = function (project_id){  
  this.now.talk();  // this will work
  Project.findOne({'_id':project_id}, (function(tunnel, err, project){
    if(project){
      this.now.talk(); 
    };
  }).bind(this, "tunnel")); // overwrite `this` in callback to refer to correct `this`
};

使用Function.prototype.bindthis的值设置为您想要的值