I’m running this in node.js. Why does the following code segment lose scope for the cb var?
Client.prototype.post = function(path, data, callback) {
var self = this;
var cb = callback;
return function() {
console.log(path);
console.log(cb);
rest.post(self.baseUrl + path, data).on('complete', cb || this.callback);
}
};
The call to this function looks like this client.post('/user', {}, function() {}); and outputs the following:
/user
undefined
I’m expecting the second line to be [Function] The returned function is probably being executed with either js’s .call() or .apply() methods to change the scope that it is run in. But I would think that cb would be accessible just like path is.
Update: Wrapping the callback in a function makes it work. But I’d still like an explanation for what’s happening here.
var cb = function() { callback(); };
It works as expected. The question is wrong all the comments are right. Someone needs to learn how to code.