oop - Refer to object method property from another method property in JavaScript -


this question has answer here:

i've got strange behavior , if can workaround i'd know why happens.

    function game () {         this.viewport = { ... };         this.player = player;         this.renderer = { ... };         this.stage = { ... };          this.init = function () {                               //this gets executed              this.setkeybindings();         }          this.run = function () {              //this works              requestanimframe(this.update);         }          this.update = function () {              //bad! throws undefined not function              //here need use reference here               this.processinput();              this.renderer.render(this.stage);              this.handlelogic();               //even 1 won't work, worked in init()!              requestanimframe(this.update);         };          //methods defined same way         this.processinput = function () {             ...         };          this.handlelogic = function () {             ...         };          this.setkeybinding = function () {             ...         }     }        

so i'm missing something:

this.setkeybindings() gets executed within init method.

this.processinput() throws error.

i don't need workaround, solved using local reference, this:

        function game () {          var reference = this;          .......          this.update = function () {              //now works              reference.processinput();              reference.handlelogic();              reference.renderer.render(reference.stage);              requestanimframe(reference.update);         }          this.init = function () {              //this 1 works using 'this'              this.setkeybindings()         }     } 

i'd know why 'this' works in methods (like init) while doesn't in others (like update).

declare local variable , assign this , use everywhere:

function game () {      var me = this;      .......      me.update = function () {          me.processinput();           me.handlelogic();           me.renderer.render(me.stage);           requestanimframe(me.update);     } } 

this solve problems references


Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -