Matt Coady Matt Coady - 2 months ago 7
Javascript Question

Keep the context of this after a click event in a function object

I've got an object with functions. Here's a simplified version:

var app = {

functOne: function(){
document.querySelector('button').addEventListener('click', this.functTwo);
},

functTwo: function(){
console.log('Funct Two has Run');
this.functThree();
},

functThree: function(){
console.log('Funct Three has Run');
}
};

app.functOne();


The app in functOne attaches a click handler to button (to launch functTwo). FunctTwo is supposed to execute FunctThree but the context of 'this' is no longer 'app' (it's now the button). How do I get 'app' again from inside (or passed to) functTwo (assuming app isn't just attached to window like in the above example).

Answer

This is achieved by using Function.prototype.bind():

  functOne: function(){
    document.querySelector('button').addEventListener('click', this.functTwo.bind(this));
  },