78

I find myself needing:

var self = this;

a lot within my javascript 'classes'. 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.

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

edit: I know exactly why I need this, I'm just wondering if it's considered a bit evil and why. I'm aware there's also the 'apply' built-in javascript function to explicitly define scope when calling a method. Is it better?

Evert
  • 75,014
  • 17
  • 95
  • 156
  • 2
    I always use `var that = this`, I honestly did not even bother looking into apply/call, but now I read about those methods, thanks for this question! – Anders Dec 06 '10 at 22:15
  • I personally think that this is not bad per se, but a sign that you could optimize your design a bit. – Dmitry Nov 30 '11 at 19:16

10 Answers10

50

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.

  • 1
    Great answer. Could you elaborate on this statement: "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"." How do you do this? – Evert Dec 07 '10 at 07:56
  • 1
    @Evert If every method is a member of the object, it will/should be invoked as some form of `obj.member` which will normally ensure the `this` is correct (since `obj->this(obj)->this(obj)->...`). If you see the Crockford link in the post, you will see that the private method approach breaks the pattern as the private "methods" are now stored in variables in the constructor and thus not invoked in the `obj.member` form. This will throw off `this` inside them (as `this` is merely the receiver of the function at time of invocation -- `obj` in the above examples) unless extra work is done. –  Dec 07 '10 at 22:08
  • 3
    `aelf` is the window object -- I would avoid using reserved words, and use `var that = this` or `var _self = this` – chovy Oct 26 '12 at 08:20
  • @chovy Interesting point I never thought of. I guess I always avoid the issue by *always* [except on the rare times I forget] using a `window.x` qualification in my code (that and I have never used `window.self` ..) –  Oct 26 '12 at 17:38
  • Be twice as evil. Put `var self = false` in the global context, then add `var self = this;` in methods where you need it. Then if ever in doubt, write `(self || this).method(...)`. It's terrible coding, but it feels good. – Orwellophile Nov 13 '16 at 16:56
17

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.

Natan Streppel
  • 5,552
  • 6
  • 31
  • 43
Peter Bailey
  • 101,481
  • 30
  • 175
  • 199
  • 4
    Sorry if I missunderstood, but it works if you do this: `setTimeout( (function() { alert( "Hi from " + this.name ); }).apply(this), 1000 ); }` – drodsou May 03 '13 at 23:13
  • @drodsou No, your code does not work, look at [this JSBin](http://jsbin.com/xayopuvoceco/1/edit?js,console). It fails with an Syntax error, because you can't just wrap something in "()" in JS. As you can see, window.setTimeout does not return a function/object, but a primitive of type "number" representing the counter's id. – Sentenza Sep 07 '14 at 23:06
  • @Peter Bailey there actually is [another way](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setTimeout#A_possible_solution), I do not say that that is a better solution, though. – Sentenza Sep 07 '14 at 23:10
  • @Sentenza I don't understand what you say. Of course setTimeout does not return a function, but that was not the intended. You do can wrap a function in () in js, and this code works ok: [JSBin](http://jsbin.com/naduqugebari/1/edit) – drodsou Sep 09 '14 at 06:59
  • Ah damnit I got your brackets wrong, sorry! You are perfectly right, I was tired :P – Sentenza Sep 09 '14 at 11:49
  • 3
    @drodsou Using apply(this) will execute function immediately thus returning undefined as first argument of setTimeout, howether there is a bind function: window.setTimeout(function () { alert( "Hi from "+this.name); }.bind(this), 1e3); – AlexanderB Apr 11 '15 at 16:28
  • Ups, you got me there @AlexanderB :-). You're totally right, it must be "bind". – drodsou Apr 12 '15 at 18:24
  • 1
    So... the way I am seeing this: using bind gives SHORTER code than the one given in this answer :). So this answer is wrong. The 'but not always' is misleading. – Adam Skobodzinski Dec 16 '16 at 12:11
  • This answer is WRONG. For the example given, it says you have to use an intermediate variable, but that is incorrect. Delayed execution binding is exactly what .bind() is for. @Peter Bailey please update your answer. – redfox05 May 14 '19 at 01:13
9

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.)

Community
  • 1
  • 1
bobince
  • 498,320
  • 101
  • 621
  • 807
7

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
AlexanderB
  • 768
  • 8
  • 11
4

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.

Patrick Karcher
  • 21,295
  • 5
  • 49
  • 65
2

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.

g.d.d.c
  • 41,737
  • 8
  • 91
  • 106
1

I think there's an argument to be made for always including var self = this in every method: human factors.

It's needed often enough that you wind up having a mishmash of methods accessing this and others using self for the same purpose. If you move code from one to the other, suddenly you get a bunch of errors.

At the same time, I catch myself absent-mindedly writing self.foo out of habit when I haven't needed or added a var self = this. So I think it could make sense to just make a habit of always including it, needed or not.

The only trouble is... this, self, or that are all an ugly pox on your code and I kind of hate them all. So I think it is better to avoid using delegated methods where possible so that you can avoid using this, that or self the vast majority of the time, and use .bind(this) when you might otherwise resort to self/that. It's very rare that using delegates on the prototype is actually going to save you any substantial amount of memory anyway.

A nice side effect of that approach is that you don't have to prefix all your private variables with _, as they will be truly private and the public properties will be called out by the leading this., making your code more readable.

As bobince said, var that = this is better because it doesn't shadow window.self. self = this sounds less awkward to me, but sometimes you get confusing error messages like property myMethod not found on global, because you forgot the self = this line.

John Starr Dewar
  • 1,351
  • 18
  • 14
1

I just want to point out that 'self' is equivalent to 'window', try outputting window === self to the console. You should use this pattern with 'that' or something similar as a variable name, avoid using 'self' since it is already in use by the browser (one mistake and you will create yourself a global variable). Even though it sounds weird, it is better to use 'that' for its name because other developers will immediately know what you were trying to accomplish in your code, avoid using nonstandard variable names. I believe that this is an important note, but it was only mentioned in one comment, so I wanted to make it more visible.

Goran Vasic
  • 997
  • 8
  • 10
  • Try to create a global variable in a browser using the self object and post a fiddle. In my browser (Chromium) this does not work, since it would define a property "self" on "window" if you would use "self = ..." without "var". – Sentenza Sep 07 '14 at 21:33
  • I am not sure why are you creating new global variable called 'self'. In JavaScript you can modify JavaScript itself, sure, but you should be extremely careful when doing so, because other developers will expect a 'standard version' of JavaScript when you provide them with your code. When you assign something to 'self', you are actually overwriting it, I would avoid doing that. I only said that when you compare default window object and self they are by default the same object. In other words, 'self' and 'window' are synonyms – Goran Vasic Sep 08 '14 at 13:43
  • _(one mistake and you will create yourself a global variable)_ – Sentenza Sep 09 '14 at 07:57
1

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;
Evert
  • 75,014
  • 17
  • 95
  • 156
0

I like it. It is "self"-explanatory. Douglas Crockford has some things to say about this. He states that using "that" is convention. You can see Crockford for free if you scoot over to yui-theater and watch hes videos about Javascript.

Phluks
  • 808
  • 1
  • 9
  • 12
  • 1
    Thank you for your feedback. I think I see what u mean. However, I dont think, that the question can be answered without a context. I happen to like the context that Douglas puts forward :) – Phluks Dec 07 '10 at 01:13