I have the following code. I expected to see “archive” object on my firebug console, but I see Window object. Is it normal?
var archive = function(){}
archive.prototype.action = {
test: function(callback){
callback();
},
test2: function(){
console.log(this);
}
}
var oArchive = new archive();
oArchive.action.test(oArchive.action.test2);
oArchive.action.test2gets you a reference to a function thatcallbackthen points to, but that function is then called usingcallback(), which means it is not called as a method and hencethisis the global object. The key point is thatthisis not bound to a function: it’s determined by how the function is called.In this case you could explicitly make
thispoint to the action object (but not the archive object) by using the callback function’scallorapplymethod:To get it
thisto be the archive object instead, you’ll need to pass the archive object in: