Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

that, self or me — which one to prefer in JavaScript?

While coding JavaScript sometimes you store the reference of object this in a local variable for different purposes (to set proper scope, to help code obfuscators, etc.). There are coders who prefer aliasing this to that to make it obvious its intention. Other guys use self since it's pointing to the object itself. I even saw source codes where me held the reference and it still makes sense. Certainly there are other ones.

Which one should I prefer? Is there a convention on which to use or is it only the matter of taste.

like image 243
viam0Zah Avatar asked Apr 23 '10 13:04

viam0Zah


People also ask

Why self is needed instead of this in JavaScript?

var self = this; In the JavaScript, “self” is a pattern to maintaining a reference to the original “this” keyword and also we can say that this is a technique to handle the events.

Is self the same as this in JavaScript?

So, within the inner function, "this" refers to the object calling the inner function while "self" refers to the object which called the outer function to create the reference to the inner function.

Can you use self in JavaScript?

You might sometimes use self to capture the context of this before it is destroyed by some function. Unfortunately self is also an alias for window , the global top-level object.


2 Answers

I, personally, use that, but anything else that's clear is fine.

I wouldn't use self because the global variable/window-property self already exists as a reference to window. Although it's totally useless (so no-one is likely to care that you're shadowing it), it slightly increases the risk of silly errors going unnoticed:

var se1f= this;         // misspelled (perniciously). or maybe you just forgot to write line
onclick= function() {
    self.foo= 1;        // whoops, just wrote to `window`!
};

whereas:

var that= this;
onclick= function() {
    that.foo= 1;        // error thrown
};

Slightly contrived, but JavaScript's so sloppy with letting errors slide you don't really want to make it any more so.

like image 122
bobince Avatar answered Nov 04 '22 02:11

bobince


There's an orange in your apple basket there, this has a very specific contextual meaning. The choice is really between self and me of those options. Between those...you choose, it doesn't matter either way only personal preference.

this refers to the context your in, so it's not really an "option" without introducing a lot of confusion and easy to make errors. I see self used much more than me (in example code, frameworks, libraries, etc). It's just preference, but I agree self is more attractive, not sure why...again just my preference.

like image 25
Nick Craver Avatar answered Nov 04 '22 03:11

Nick Craver