I often see this in code: var me = this;
. Why is that? Is there some performance gain if I reference 'this' in local variable?
It's useful if there are functions inside a function, such that code in those nested functions needs access to the value of this
from the outer context.
function example() {
var me = this;
document.getElementById('whatever').onclick = function() {
me.clicked = 1;
};
}
Because this
is established anew for every function call, without stashing the outer this
in a variable there'd be no way to reference it at all from the inner function.
This is used to save reference to this
. Later in the code there's an AJAX call with a callback (for example). So, inside of that callback this
is not the same as outside. That's why people back up "outer" this
to a variable.
I personally like to use this form:
var that = this;
Looks funny :)
By the way, CoffeeScript, which is a kind of "javascript done right", has a fix for this as well.
It has two forms for function definition, thin arrow and fat arrow. Thin arrow behaves exactly like in javascript, and fat arrow automatically binds this
to a value from outer context.
So, this coffeescript
Account = (customer, cart) -> # thin arrow
@customer = customer
@cart = cart
$('.shopping_cart').bind 'click', (event) => # fat arrow
@customer.purchase @cart
gets transformed to this javascript
var Account;
Account = function(customer, cart) {
var _this = this;
this.customer = customer;
this.cart = cart;
return $('.shopping_cart').bind('click', function(event) {
return _this.customer.purchase(_this.cart);
});
};
Cool, isn't it?
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