Search code examples
javascriptstrict

Access common value in call back in strict mode


I have accessed common value in call back like this.

function InfoClass() {
    var local = 1;
    self = this;
}
InfoClass.prototype.myFunction = function (){
    this.win.addEventListener('open', function(e){
          // I can't use 'this' here. 
        self.local // So I access common value in callback like this.
    });
}

Before strict mode it works,

However ,now I need to set strict mode, so it shows error self doesn't have var.

Is there any alternative way??


Solution

  • You can try following

    InfoClass.prototype.myFunction = function (){
        var self = this;
        this.win.addEventListener('open', function(e){
            self.local // you can access the function now
        });
    }
    

    Or you can use arrow function like following

    InfoClass.prototype.myFunction = function (){
        this.win.addEventListener("open", (e) => {
             this.local // you can use this now
        });
    }
    

    For reference, Arrow functions