Access this inside event

Asked

Viewed 52 times

4

How can I access the this concerning my object, when it calls an event? When the event is called, the this becomes the event itself, the 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 inside the callback of the event keypress?

2 answers

7


You need to "set" the scope of the anonymous function that the event receives, to do this use the .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);
}

1

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

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

or if you need the event parametere

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

I really like this approach for making the code cleaner

Browser other questions tagged

You are not signed in. Login or sign up in order to post.