Reputation: 1234
Ok, so I have a node application that uses express. Within this application I have an express route like so:
var MyObj = require('./myObj')
, myObj = new MyObj();
app.post('/api/blah', auth.requiresLogin, myObj.method2);
Now within the MyObj object I have the following:
var MyObj = function(name){
this.name = name;
this.message = 'hello';
};
MyObj.prototype = {
method1: function(req, res, done){
console.log('In Method 1');
done(null, this.message +' '+this.name);
},
method2: function(req, res){
var message;
console.log('In Method 2');
this.method1(req, res, function(err, value){
if(err) throw err;
message = value;
console.log(this.message);
});
return message;
}
};
module.exports = MyObj;
Now if I dont require this object and call it from within the same file it works. As demonstrated on this jsFiddle: http://jsfiddle.net/britztopher/qCZ2T/. However, if i require it, construct it with new, and try to call myObj.method2(req, res);
from the requiring class I get #<Object> has no method 'method1'
. Dont know what I am doing wrong here, or if its expressJS or require JS thats giving me issues. Also, when i look inside this
when in method2 it is this = global
, so something is losing this' context.
Upvotes: 2
Views: 871
Reputation: 2799
When passing the myObj.method2
method as a parameter to app.post
you are not telling in which context/scope it should execute. Therefore it will execute in the global scope. The solution should be myObj.method2.bind(myObj)
.
Upvotes: 1