-2

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?

Amruth
  • 5,792
  • 2
  • 28
  • 41
simplywing
  • 19
  • 4

3 Answers3

0

You just forgot to return from call1. Add return and it will work as expected:

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

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

var a = new obj()
console.log( a.call1() )
dfsq
  • 191,768
  • 25
  • 236
  • 258
0

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();
   }
}
Arun Ghosh
  • 7,634
  • 1
  • 26
  • 38
0

Maybe you meant this:

const obj = {
  var1: 'var1'
 ,getvar1() {
    return this.var1
  }
 ,call1() {
    return this.getvar1()
  }
}

console.log(obj.call1())
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177