JavaScript (node.js) variable not accessible on inner function call. now.js
I am using now.js and Mongoose i开发者_如何学Pythonn a node project and am having trouble accessing the this.now object inside of a mongoose function. 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"
};
});
};
Change the code to this:
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
};
});
};
Inside your inner function, the this
is probably being set to something else. So, to preserve the value you want to access, you assign it to a different local variable that will be available in the inner function.
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`
};
Use Function.prototype.bind
to set the value of this
to the value you want
精彩评论