What is the common way to preserve the context of this
?
What is faster? What would you prefer?
$.proxy(...)
$('a').on('click', $.proxy(function() {
this.close();
}, this));
var self
var self = this;
$('a').on('click', function() {
self.close();
});
Let's start by fixing your code. You have a useless function declaration, you may use $.proxy
as
$('a').on('click', $.proxy(this.close, this));
Now, the second solution based on self
self
variableThat's probably why it's more used.
Note that when you don't have to be compatible with IE8, you may use bind :
$('a').on('click', this.close.bind(this));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With