Used to save links to this . Later in the code there is an AJAX call with a callback (for example). Thus, inside this callback, this does not match the external. This is why people support the "external" this for a variable.
I personally like to use this form:
var that = this;
It looks funny :)
By the way, CoffeeScript , which is a kind of "javascript done right", also has a fix for this.
It has two forms for determining function, a thin arrow and a fat arrow. The thin arrow behaves exactly the same as in javascript, and the bold arrow automatically binds this to a value from the external context.
So this coffeescript
Account = (customer, cart) ->
converted 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, right?
source share