oop - Access instance variable inside a function in javascript? -


how can in easiest way access instance variable inside function?

function myobject(){       //instance variables      this.handler;       //methods      this.enablehandler = function(){          var button = document.getelementbyid('button');          button.onclick = function(){              this.handler();//is not working          }      }  } var myobject = new myobject(); myobject.handler = function(){     alert('hello world!'); } myobject.enablehandler(); 

note can set button.onclick = this.handler;. example. main question how can access this.handler inside function?

i can define new variable var handler = this.handlerto access this.handler. if change handlerwill this.handler changes?

function myobject(){       //instance variables      this.handler;      var = this;  //notice change      //methods      this.enablehandler = function(){          var button = document.getelementbyid('button');          button.onclick = function(){              that.handler();//is not working  notice change          }      }  } var myobject = new myobject(); myobject.handler = function(){     alert('hello world!'); } myobject.enablehandler(); 

if assign var within scope of outer function, passed inner functions scope chain. within inner function referencing refers inner function, referencing variable assigned this, in our case "that", refers object.


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

c# - SharpSVN - How to get the previous revision? -

php cli reading files and how to fix it? -