Search code examples
javascriptobjectthisobject-literal

Unable to access "this" inside an object litteral


I'm having a hard time understanding how I could access a this located inside one of the methods of an object literal I created.

Here is an example:

var app = {
  click: function(e) {
    e.preventDefault();
    console.log('Clicked');
    this.saywhat();
  },

  saywhat: function() {  
    console.log('Say what ?');
  }
};

var link = document.querySelector('a');
link.addEventListener('click', app.click);

If I click on the link, I get this error: Uncaught TypeError: this.saywhat is not a function. How can I make saywhat() available from inside click()? (I would like to find a solution where I'm not forced to use app.saywhat())


Solution

  • That's because this in event handlers is the element that the event was registered with, i.e, link.

    In your case, you can use app.saywhat(), or you can explicitly specify what to use as this by using Function.prototype.bind. That is,

    link.addEventListener('click', app.click.bind(app));