javascript - Why isn't this recognized as a function? -
i have function in object:
var time = { warps : 3, warpcounter : 50, warp : function(){ if (this.warps > 0){ this.warps--; this.warploop = 50; this.warploop(); } }, warploop : function(){ settimeout(function () { this.increment(); if (warpcounter--){ this.warploop(); }else{ if(this.warps > 0){ htmlinteraction.enablebutton('warp-button'); } } }, 100); }, };
when try , call method (using this.warploop()
) get:
uncaught typeerror: property 'warploop' of object #<object> not function
why this?
this context in settimeout changes, can use closures keep context.
var test={ warploop : function(){ var me=this;//set closure right context settimeout(function () { console.log("this is:",this); // window console.log("me is:",me); // test // can call me.warploop() not this.warploop() }, 100); } } test.warploop();
your code can this:
var time = { warps : 3, warpcounter : 3, warp : function(){ if (this.warps > 0){ this.warps--; this.warploop = 50; this.warploop(); } }, warploop : function(){ //the settimeout calls me.warpcounter not this.warpcounter // wich same window.warpcounter since next // line not part of settimeout execution can // use console.log("warploop called,warpcounter is",this.warpcounter); var me=this; settimeout(function () { //me.increment(); if (me.warpcounter--){ me.warploop(); }else{ if(me.warps > 0){ //htmlinteraction.enablebutton('warp-button'); } } }, 100); }, }; time.warploop();
Comments
Post a Comment