Access this within event

4

How can I access the this relative to my object, when it calls an event? When the event is called, this becomes the event itself, window.event

Ex:

function Foo() {
     this.bar = function() {
        console.log('Hi!');
     }

    document.onkeypress = function(e) {
        // Aqui, o "this" não é mais o objeto Foo, mas sim o "e" ou "window.event"
        this.bar();
        // Erro: this.bar não está definido... 
    }
}

How can I access my object from within callback of event keypress ?

    
asked by anonymous 26.07.2017 / 00:05

2 answers

7

You need to "set" the scope of the anonymous function that the event receives, to do this use .bind() , following example:

function Foo() {
     this.bar = function() {
        console.log('Hi!');
     }
    //Com esse método você passa pelo parâmetro o escopo que a função tera,que no caso é this mesmo.
    document.onkeypress = function(e) {
        this.bar();
    }.bind(this);
}
    
26.07.2017 / 00:20
1

If you are using ES6 or some transpiler, the Arrow Function can be a solution as well. They have this of the context they are bound to, basically the context from where it was declared.

function Foo() {
  this.bar = function() {
    console.log('Hi!');
  }
  document.onkeypress = () => { this.bar() } 
}

or if you need the event parameter e

document.onkeypress = e => { this.bar() } 

I really like this approach by leaving the code cleaner

    
26.07.2017 / 04:42