Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I reference 'this' in local variable?

I often see this in code: var me = this;. Why is that? Is there some performance gain if I reference 'this' in local variable?

like image 559
ilija139 Avatar asked Dec 04 '22 04:12

ilija139


2 Answers

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.

like image 51
Pointy Avatar answered Dec 22 '22 04:12

Pointy


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?

like image 38
Sergio Tulentsev Avatar answered Dec 22 '22 03:12

Sergio Tulentsev