0

got an issue with accessing an object parameter in a function of the object if I pass this function as parameter and then call it.I.e. in below code I had expected that this.radius == 100 is always true. Hover in test3 below it is not if beforehand I pass test3 as parameter. Any idea why and how I can access the variable there?

Cheers Tom

Test = function ( ) {
    var self = this;

    this.radius = 100;
    this.test1();
}
Test.prototype.test1 = function() {
    console.log("test1 - this"+this.radius);// this.radius==100
    console.log("test1 - self"+self.radius);// self.radius==undefined
    this.test2(this.test3);
}

Test.prototype.test2 = function (func){
    console.log("test2- this"+this.radius);// this.radius==100
    console.log("test2- self"+self.radius);// self.radius==undefined
    func();// calling the function passed as parameter
}

Test.prototype.test3 = function (){
    console.log("test3- this"+this.radius);// this.radius==undefined
    console.log("test3- self"+self.radius);// self.radius==undefined
}
TomFree
  • 1,091
  • 3
  • 17
  • 31
  • `this` in `test3` isn't what you think it is, when you call the function with a different context. Notice also, that functions in prototypes can't access local variables in `Test`, i.e. `self` refers to `window` in the methods. – Teemu Aug 25 '16 at 19:07
  • You need to use `this.test3.bind(this)` so that it keeps its context. – Barmar Aug 25 '16 at 19:08

1 Answers1

2

A function only gets its context from the value before the . if you call the function that way, i.e. you write this.test3(). Creating a function reference with this.test3 doesn't bind the context. To do that, you need to call .bind() explicitly:

this.test2(this.test3.bind(this));
Barmar
  • 741,623
  • 53
  • 500
  • 612