0

I was wondering. I've got a button from where I call a function when pressed. I use JQuery to do this as such:

this.chose_button.on('click', function() {
  tryInputSong(this, this.link_input.val());
});

the problem though is that I need the input parameter for "tryInputSong" to be the same object as the "this" keyword in "this.chose_button" not as the "this.chose_button" object itself. Is there a way I can stop the "this" keyword from changing the value to this.chose_button or must I in some way pass my wanted object through another function?

I am really confused about to solve this and I would appreciate some help, thank you! :)

3 Answers3

3

JS introduced arrow functions to allow you to reference the outer this value.

this.chose_button.on('click', event => 
  tryInputSong(this, this.link_input.val())
);

Because arrow functions don't bind their own local this, it uses the one from the outer environment.

The syntax I show above has a single expression as the function body. If you need multiple statements, then you define the body with curly braces, just like with traditional function syntax.

You can still get reference to the bound element via event.currentTarget.

2

The usual old-school work-around is storing a reference to this from the context you want and reuse it later:

var self = this;
this.chose_button.on('click', function() {
  tryInputSong(self, self.link_input.val());
});

You can also explicitly bind the value of this on your function:

this.chose_button.on('click', function() {
  tryInputSong(this, this.link_input.val());
}.bind(this));

Or if your environment supports ES6 arrow functions (or you use a transpiler adds the corresponding polyfills), then you can use an arrow function which doesn't change the binding of this

this.chose_button.on('click', () => {
  tryInputSong(this, this.link_input.val());
});
elyalvarado
  • 1,226
  • 8
  • 13
0

You can do it like this:

var self = this;
this.chose_button.on('click', function() {
  tryInputSong(self, self.link_input.val());
});

Or use arrow functions: An arrow function does not have its own this; the this value of the enclosing execution context is used

ferralucho
  • 637
  • 7
  • 24