Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is var self = this; a bad pattern?

Tags:

javascript

As others have said: This "extra variable" is (at some level) the only way to get about the fact that this is a special expression and thus, being not a variable, is not bound in an execution context/closure.

However, what I think you are asking (or what I really want to answer) is:

Should one put var self = this at the top of every method/constructor?

Summary

While I tried this once, and had the same question, I no longer use this approach. Now I reserve the construct for when I need access in a closure. To me it adds a little "hey, this is what I really want!" semantic to my code:

this -> this and self -> this (but really that) in a closure

Questions ala carte:

...Although this is commonly done, it feels a bit wrong. What I'm hoping to find in this question is a better way to deal with this, or a something to convince me this is quite alright.

Do what feels right to you. Don't be afraid to try one method and switch back later (but please try to remain consistent within each project :-)

Is this the standard way to keep the correct bindings around? Should I standardize on using 'self' everywhere, unless i explicitly need 'this'.

"self" is the most common name used. As per above, I prefer the opposite approach -- to use this except when a closure binding is required.

..if it's considered a bit evil and why.

Evil is a silly subjective term (albeit fun sometimes). I've never said it was evil, just why I do not follow the approach. Some people tell me I am "evil" for not using semi-colons. I tell them they should actually come up with good arguments and/or learn JavaScript better :-)

I'm aware there's also the 'apply' built-in javascript function to explicitly define scope when calling a method. Is it better?

The problem with apply/call is that you must use them at point of the function invocation. It won't help if someone else calls one of your methods as the this may already be off. It's most useful for doing things like the jQuery-style callbacks where the this is the element/item of the callback, etc.

As an aside...

I like to avoid "needing self" on members and thus generally promote all member functions to properties where the receiver (this) just "flows through", which is normally "as expected".

The "private" methods in my code begin with a "_" and if the user calls them, that's on them. This also works better (is required, really) when using the prototype approach to object creation. However, Douglas Crockford disagrees with this "private" approach of mine and there are some cases where the look-up chain may thwart you by injecting an unexpected receiver:

Using the "self" bound in the constructor also locks the upper limit of the look-up chain for a method (it is no longer polymorphic upward!) which may or may not be correct. I think it's normally incorrect.

Happy coding.


Yes, this is the standard way.

Function.apply() and Function.call() can help, but not always.

Consider the following

function foo()
{
  var self = this;
  this.name = 'foo';

  setTimeout( function()
  {
    alert( "Hi from " + self.name );
  }, 1000 );       
}

new foo();

If you wanted to do this but avoid the usage of a variable like self and use call() or apply() instead... well... you look at it and start to try, but soon realize you just can't. setTimeout() is responsible for the invocation of the lambda, making it impossible for you to leverage these alternate invocation styles. You'd still end up creating some intermediary variable to hold a reference to the object.


Is this the standard way to keep the correct bindings around?

There is no standard, where JavaScript and class/instance systems are concerned. You will have to choose what kind of object model you prefer. Here's another link to a backgrounder; conclusion: there is no conlusion.

Typically keeping a copy var self= this;(*) in a closure goes hand-in-hand with an object model built around closures with per-instance copies of each method. That's a valid way of doing things; a bit less efficient, but also typically a bit less work than the alternative, an object model built around prototyping, using this, apply() and ECMAScript Fifth Edition's bind() to get bound methods.

What could be counted more as ‘evil’ is when you have a mish-mash of both styles in the same code. Unfortunately a lot of common JS code does this (because let's face it, no-one really understands JavaScript's bizarre native object model).

(*: I typically use that instead of self; you can use any variable name you like, but self already has an somewhat obscure and completely pointless meaning as a window member that points to the window itself.)


Just came across this question because my coworkers addicted to self/that variables and I wanted to understand why...

I think there is a better way to deal with this in nowdays:

function () {}.bind(this);      // native
_.bind(function () {}, this);   // lodash
$.proxy(function () {}, this);  // jquery

In javascript and other languages with closures, this can be a very important thing to do. The object that this refers to in a method can actually change. Once you set your self variable equal to this, then self will reliably remain a reference to the object in question, even if this later points to something different.

This is an important difference in javascript compared to many other languages we work in. I'm coming from .Net, so this type of thing seemed strange to me at first too.

Edit: Ah, okay, you know all that. (maybe still helpful for someone else.) I'll add that Apply (and Call) are more for using from "the outside", giving to a function you're calling a specific scope that you already know about. Once you're inside a function and you're about to cascade further down into closures, the technique:

  var self = this;

is the more appropriate way (easy and clear) way to anchor your current scope.


It's 6 years later, and I have some things to add myself:

bind() is now common enough to be used everywhere. I use it often as an alternative. Sometimes it feels clearer. I still on occasion use var self = this;. though.

Arrow functions slowly are becoming viable for usage. The syntax is a bit shorter which is nice, but I think the killer feature really is that by default they always bind to the parent scope.

This:

var self = this;
var foo = function(a) {

  return self.b + a;

};

Can now be written as :

var foo = a => this.b + a;

This is the 'most optimistic' usage of arrow functions, but it's pretty sweet.

And just to concluse, there's nothing wrong with:

var self = this;

Most likely this is done as a way to maintain a reference to this when the scope is about to change (in the case of a closure). I don't know that I'd consider it a bad practice or pattern in and of itself, no. You see similar things a lot with libraries like jQuery and a great deal with working with AJAX.