Matt Coady Matt Coady - 1 year ago 64
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');

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


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 Source

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

  functOne: function(){
    document.querySelector('button').addEventListener('click', this.functTwo.bind(this));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download