javascript - `this` is undefined when calling method from another context -


this first time creating oop js. followed tutorials can't wrap head around issue. know problem, dont know solution

function newapp(name){     this.name = name;     this.currentpage = 1;     this.customobjectwithmethods = //init options , on }  newapp.prototype.logic = function(){ // note 1.       var app =     //note 3.     this.customobjectwithmethods.method{         if(app.currentpage < 3)             // note 2.               app.navigate(app.logic)     } }  newapp.prototype.navigate = function(sender){     var app = this;     this.customobjectwithmethods.method{         app.currentpage++;         this.method(function() {             return app.currentpage === 2;         }, sender(), this.terminate);     }  } 
  • note 1: need create reference because after that, this doesn't work anymore refer current object.
  • note 2: after check want logic in method , repeat current function, when function runs again breaks on method (this.customobjectwithmethods) because this doesn't exists.
  • note 3: breaks because "this" works first time not second time.

it gets complicated this-keyword, makes me think design may flawed.

is there solution problem, or should refactor ?

surely become complicated, thiskeyword doesn't refer main object scope used, take @ scope , in javascript further information.

this way go, make variable contains constructor , add these 2 methods variable, after can call functions:

var newapp = function newapp(name){     this.name = name;     this.currentpage = 1;      //make reference object here     var = this;      this.logic = function(){          var sender = this;          this.customobjectwithmethods.method = function(){             if(this.currentpage < 3)                  this.navigate(sender);         }     }      this.navigate = function(sender){         this.customobjectwithmethods.method = function(){             this.currentpage++;             this.method(function() {                 return this.currentpage === 2;             }, sender(), this.terminate);         }      }      } 

and how use constructor , methods:

var app = newapp("test");  //call first method app.customobjectwithmethods();  //thenn call second 1 app.logic(); 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -