Javascript this points to Window object -


i have following code. expected see "archive" object on firebug console, see window object. 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.test2 gets reference function callback points to, function called using callback(), means not called method , hence this global object. key point this not bound function: it's determined how function called.

in case explicitly make this point action object (but not archive object) using callback function's call or apply method:

test: function(callback) {     callback.call(this); }, 

to this archive object instead, you'll need pass archive object in:

var archive = function(){}  archive.prototype.action = {     test: function(callback, archive){         callback.call(archive);     },     test2: function(){         console.log(this);     } }  var oarchive = new archive(); oarchive.action.test(oarchive.action.test2, oarchive); 

Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -