0

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).

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Matt Coady
  • 3,418
  • 5
  • 38
  • 63

1 Answers1

1

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

  functOne: function(){
    document.querySelector('button').addEventListener('click', this.functTwo.bind(this));
  },
itdoesntwork
  • 4,666
  • 3
  • 25
  • 38