Should I Reference 'this' In Local Variable?
Solution 1:
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.
functionexample() {
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.
Solution 2:
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
varAccount;
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?
Solution 3:
It is so that when this
changes, you still have a reference to this
at the point in the code you need.
Solution 4:
IMO it's unusual you'd see that on its own--it's a construct almost always used when there are closures involved to avoid JS's treatment of the this
value, evaluated during execution, not declaration.
Solution 5:
That is often used for callback methods, where the scope would be different when the callback runs.
Example:
var me = this;
$.getJSON(url, function(data) {
// here "this" will be "window", so "me" is used to access the object
})
Post a Comment for "Should I Reference 'this' In Local Variable?"