simplywing simplywing - 7 days ago 7
Javascript Question

Javascript access public methods from inside other public methods (same Object)

I have the following JS-Object:

var obj = function(){
this.var1 = "var1";

this.getvar1 = function(){
return this.var1;
}
this.call1 = function(){
this.getvar1();
}
}



  • all methods have to be public

  • all properties have to be public as well



Problem:

If i try to call a public method of the obj-Object from inside another public method of the obj-Object, the "this" keyword refers to the public method itself instead of the Object.

Is there a way to get around this?

Answer

You can assign this to a variable(self) and use that:

var obj = function(){
   var self = this;
   self.var1 = "var1";

   self.getvar1 = function(){
       return self.var1;
   }
   self.call1 = function(){
       self.getvar1();
   }
}
Comments