-1

how can I access a fiel from within an anonymous function inside a method? like in this example:

class Something {
    constructor (){
        this.gax = “gax”;
    }
    doSomething(){
        (function () {
           console.log(this.gax);
        }());
    }
}
new Something().doSomething();

this will result in an error that "this" is undefined. thank you very much in advance, I could not find an answer in the web after searching for hours. best, lev

Lev
  • 3
  • 3
  • 2
    sorry but what you need the anonymous function for? – youssef ali Nov 22 '19 at 15:40
  • Probably relevent: [another SO answer](https://stackoverflow.com/questions/2236747/what-is-the-use-of-the-javascript-bind-method) – Dale Nov 22 '19 at 15:45
  • ...or possibly [access correct 'this' in a callback](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) ...or about a half-dozen others, incl the one mentioned by @Dale. – Jared Smith Nov 22 '19 at 15:49

2 Answers2

0

In your anonymous function, this is bound to the function; it no longer refers to the class.

Use an arrow function instead, which doesn't have it's own this binding.

class Something {
    constructor (){
        this.gax = "gax";
    }
    doSomething(){
        (() => {
           console.log(this.gax);
        })();
    }
}
new Something().doSomething();

Alternatively, you could use something like .call(), .apply(), or .bind():

class Something {
    constructor (){
        this.gax = "gax";
    }
    doSomething(){
        (function() {
           console.log(this.gax);
        }).call(this);
    }
}
new Something().doSomething();
Tyler Roper
  • 20,529
  • 6
  • 30
  • 51
0
class Something {
    constructor (){
        this.gax = "gax";
    }
    doSomething(){
        (function () {
           console.log(this.gax);
        }).apply(this);
    }
}
new Something().doSomething();

You can use apply method. The apply() method calls a function with a given this value

Saurabh Yadav
  • 3,015
  • 1
  • 7
  • 20