what is var self = this; ?

6,391 views
Skip to first unread message

Dominic Tarr

unread,
Oct 26, 2010, 7:03:48 PM10/26/10
to nod...@googlegroups.com
what is the purpose of 

self = this

I've seen it a bunch of times now, but not 100% sure what it's for.

is it so that functions in a object retain access to the object's prototype/instance and would 'this' point to the prototype object of a function if it is not initialized with new?

Keith Pitt

unread,
Oct 26, 2010, 7:07:59 PM10/26/10
to nod...@googlegroups.com
You usually do that when you want to reference scope of another object. For example:

var functionX = function() {
  var self = this;
  var functionY = function(y) {
    // If we call "this" in here, we get a reference to functionY,
    // but if we call "self" (defined earlier), we get a reference to
    // function X.
  }
}

Does that make sense?

Keith Pitt
Web: http://www.keithpitt.com
Twitter: @keithpitt
Skype: keithpitt
Phone: +61 432 713 987


--
You received this message because you are subscribed to the Google Groups "nodejs" group.
To post to this group, send email to nod...@googlegroups.com.
To unsubscribe from this group, send email to nodejs+un...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/nodejs?hl=en.

Marak Squires

unread,
Oct 26, 2010, 7:10:18 PM10/26/10
to nod...@googlegroups.com
It's a way of maintaining the scope of "this" inside another scope.

"self" is arbitrary, you could call it "foo" if you wanted.

Ryan Gahl

unread,
Oct 26, 2010, 7:18:26 PM10/26/10
to nod...@googlegroups.com
var me = this; //FTW

'me' is 50% less typing than 'self'. so obvious that it's better.

pffffffshhhhhh.

:P

James Carr

unread,
Oct 26, 2010, 7:07:40 PM10/26/10
to nod...@googlegroups.com
It's related to scoping. If you have a callback called within the
scope of a function this resolves to the callback, not the outer
scope. self = this is a way of referencing the outer scope.

It's an idiom from callbacks in client side js since way back (first
time I used it was with XHR back in 2004). :)

Thanks,
James

Jacob Rothstein

unread,
Oct 26, 2010, 7:53:16 PM10/26/10
to nod...@googlegroups.com
I know this is a style thing, but IMHO there's always a better name
for the var than "self." Using something descriptive like "button" or
"person" or "user" etc works just as well for scoping, but is way
easier to read. "Self" is ruby, not js, and the concept doesn't
translate directly. var that = this and var me = this are just as bad
in that they don't describe what the variable contains. When you read
your code later (or hand it to someone else), the meaningful var name
will help.

Just 2¢,
–Jacob

Dominic Tarr

unread,
Oct 26, 2010, 8:00:48 PM10/26/10
to nod...@googlegroups.com
I see you 50% less typing and raise you another 50%

var i = this

actually, I go all in:

I don't think var x = this is necessary at all:

function who1() {return this;}
who1()
//return {}
//ab object, not the function what about this:
function who2() {return this.constructor;}
//so, i'd expect:
who2 == who2()
//false
//where does it point?
this.constructor == who2()
//true
//seems 'this' does not change to point to who2...
//but if you do this:
who2 == new who2()
//true

so if you don't use new, you don't get a new this.

so normal functions don't need self = this, but prototypes inside prototypes which want to refur to the outside prototype do.

Orlando Vazquez

unread,
Oct 26, 2010, 8:32:25 PM10/26/10
to nod...@googlegroups.com

Someone please correct me if I'm wrong, but JavaScript only has
function scope and global scope. If a variable is not found in the
current scope, JavaScript keeps going up in scopes until it finds that
variable or decides it doesn't exist. This is the case for most
variables, with the exception of `this` and `arguments`, which ALL
functions get. (There may be more, but I dont remember offhand)
Typically `this` can come from an instantiated object that's had a
method called on it, or someone doing a Fn.apply or Fn.call with an
explicit target object. (eg myfunction.apply(myobject, args) => this =
myobject)

Therefore, in order to "hold onto" a previous scope, we just assign it
to `self`. You may a few layers deep in callbacks involving multiple
objects, where it's useful to retain a handle on the top-most object
which you can use in callbacks. Like others have posted here, the name
`self` isn't magical (unlike `this`, which is), you could call it
whatever you want, it's just a convention that's sprung up...

--
Orlando Vazquez

Stephen Belanger

unread,
Oct 26, 2010, 8:49:35 PM10/26/10
to nod...@googlegroups.com
Here's a fun little example to demonstrate exactly what "var self = this" is used for;

var first = {
    exec: function(){
        var self = this;
        var second = {
            exec: function(){
                console.debug(self.level); // returns 1, because "self" was created as a pointer to the "first" object.
                console.debug(this.level); // returns 2, because "this" was silently created in the object constructor as a pointer to the "second" object.
            }
            , level: 2
        };
        second.exec();
    }
    , level: 1
};
first.exec();

Dominic Tarr

unread,
Oct 26, 2010, 8:49:52 PM10/26/10
to nod...@googlegroups.com
ah, good point

if something called your callback using fn.apply(newThis,args) the value of 'this' would be unexpected, 

so to be safe using self = this is a good idea. 

otherwise you could get some very hard to diagnose bugs.


--

Ryan Gahl

unread,
Oct 26, 2010, 9:47:44 PM10/26/10
to nod...@googlegroups.com
Also, I like semicolons;




NEW GAME: saying "I like(don't like) semicolons;" === Rick Rolling the audience while pointing out banality of continuing current discussion; that it has morphed into a redundant or purely opinion based state.

Dominic Tarr

unread,
Oct 26, 2010, 10:12:45 PM10/26/10
to nod...@googlegroups.com
forgive me for being anal about wanting to understand the nitty gritty, 

but I'm a computer programmer.

Ryan Gahl

unread,
Oct 26, 2010, 10:17:29 PM10/26/10
to nod...@googlegroups.com
no no, not anal... banal


also, you are forgiven :)
Message has been deleted

Ricardo Tomasi

unread,
Oct 26, 2010, 10:28:09 PM10/26/10
to nodejs
I like turtles.

The self, one's das Über-Ich, comprises the organised part of the
personality structure.

"The super-ego retains the character of the father (...)"
—Freud, The Ego and the Id (1923)

This is very common in jQuery land, where you're usually dealing with
a most important element in the code block:

$('.allsomething').each(function(){
var self = this;

$(self).find('a').hover(function(){
makeFries( self );
}, function(){
self.analyze();
});

});

On Oct 26, 11:47 pm, Ryan Gahl <ryan.g...@gmail.com> wrote:
> Also, I like semicolons;
>
> NEW GAME: saying "I like(don't like) semicolons;" === Rick Rolling the
> audience while pointing out banality of continuing current discussion; that
> it has morphed into a redundant or purely opinion based state.
>
> On Tue, Oct 26, 2010 at 7:49 PM, Dominic Tarr <dominic.t...@gmail.com>wrote:
>
>
>
>
>
>
>
> > ah, good point
>
> > if something called your callback using fn.apply(newThis,args) the value of
> > 'this' would be unexpected,
>
> > so to be safe using self = this is a good idea.
>
> > otherwise you could get some very hard to diagnose bugs.
>
> > On Wed, Oct 27, 2010 at 1:32 PM, Orlando Vazquez <ovazq...@gmail.com>wrote:
>
> >> On Tue, Oct 26, 2010 at 4:03 PM, Dominic Tarr <dominic.t...@gmail.com>
> >> nodejs+un...@googlegroups.com<nodejs%2Bunsu...@googlegroups.com>
> >> .
> >> For more options, visit this group at
> >>http://groups.google.com/group/nodejs?hl=en.
>
> >  --
> > You received this message because you are subscribed to the Google Groups
> > "nodejs" group.
> > To post to this group, send email to nod...@googlegroups.com.
> > To unsubscribe from this group, send email to
> > nodejs+un...@googlegroups.com<nodejs%2Bunsu...@googlegroups.com>
> > .

CC

unread,
Oct 27, 2010, 2:53:19 AM10/27/10
to nod...@googlegroups.com
Here a small source from Facebook which avoid having multi self/this
for more readable code :

function bind(d, c) {
var a = Array.prototype.slice.call(arguments, 2);
var b = function () {
var f = d || (this == window ? false : this),
e = a.concat(Array.prototype.slice.call(arguments));
if (typeof(c) == "string") {
if (f[c]) return f[c].apply(f, e);
} else return c.apply(f, e);
};
if (typeof c == 'string') {
b.name = c;
} else if (c && c.name) b.name = c.name;
return b;
}

Function.prototype.bind = function (b) {
var a = [b, this].concat(Array.prototype.slice.call(arguments, 1));
return bind.apply(null, a);
}

And you write :

setTimeout(function(){ this.do_tuff_with }.bind(this), 10);

Or :

something.click(this.method.bind(this, 1234));

And not :

var self = this;
something.click(function(){
self.method(1234);
});

2010/10/27 Ricardo Tomasi <ricar...@gmail.com>:
> I like turtles.
>
> The self, one's "das Über-Ich", comprises the organised part of the


> personality structure.
>
>    "The super-ego retains the character of the father (...)"
>      —Freud, The Ego and the Id (1923)
>

> It is very common in jQuery land, where you're usually dealing with a


> most important element in the code block:
>
> $('.allsomething').each(function(){
>    var self = this;
>
>    $(self).find('a').hover(function(){
>        makeFries( self );
>    }, function(){
>        self.analyze();
>    });
>
> });
>

> In node you'll usually be dealing with a lot more deep nesting, so
> 'self' will often not be the best choice, but it's the same idea.


>
> On Oct 26, 11:47 pm, Ryan Gahl <ryan.g...@gmail.com> wrote:

>> Also, I like semicolons;
>>
>> NEW GAME: saying "I like(don't like) semicolons;" === Rick Rolling the
>> audience while pointing out banality of continuing current discussion; that
>> it has morphed into a redundant or purely opinion based state.
>>

>> On Tue, Oct 26, 2010 at 7:49 PM, Dominic Tarr <dominic.t...@gmail.com>wrote:
>>
>>
>>
>>
>>
>>
>>
>> > ah, good point
>>
>> > if something called your callback using fn.apply(newThis,args) the value of
>> > 'this' would be unexpected,
>>
>> > so to be safe using self = this is a good idea.
>>
>> > otherwise you could get some very hard to diagnose bugs.
>>

>> > On Wed, Oct 27, 2010 at 1:32 PM, Orlando Vazquez <ovazq...@gmail.com>wrote:
>>
>> >> On Tue, Oct 26, 2010 at 4:03 PM, Dominic Tarr <dominic.t...@gmail.com>

>> >> nodejs+un...@googlegroups.com<nodejs%2Bunsu...@googlegroups.com>


>> >> .
>> >> For more options, visit this group at
>> >>http://groups.google.com/group/nodejs?hl=en.
>>
>> >  --
>> > You received this message because you are subscribed to the Google Groups
>> > "nodejs" group.
>> > To post to this group, send email to nod...@googlegroups.com.
>> > To unsubscribe from this group, send email to

>> > nodejs+un...@googlegroups.com<nodejs%2Bunsu...@googlegroups.com>

francisco treacy

unread,
Oct 27, 2010, 3:40:33 AM10/27/10
to nod...@googlegroups.com
For those who want to save characters, there's CoffeeScript:

something.click => @method(1234)

instead of:

var self = this;
something.click(function(){
self.method(1234);
});


2010/10/27 CC <coman...@gmail.com>:

Robert Kieffer

unread,
Oct 27, 2010, 8:57:54 AM10/27/10
to nodejs
A general word of caution about using "self"...

In browsers, "self" is pre-defined to refer to the current window
object:

https://developer.mozilla.org/en/DOM/window.self

Hence, I prefer "me" if/when doing this sort of thing.

Micheil Smith

unread,
Oct 27, 2010, 9:07:47 AM10/27/10
to nod...@googlegroups.com
Robert:

In this case it doesn't matter, window.self == this in global scope,
which in turn this == window in global scope. See:

> self
DOMWindow
> this
DOMWindow
> this == window
true
> this == window.self
true

I'd see that as an endorsement for self = this;

Yours,
Micheil Smith
--
BrandedCode.com

Zhami

unread,
Oct 27, 2010, 9:40:10 AM10/27/10
to nodejs
"this" is an interesting entity in JavaScript functions; its value in
a function depends on the nature of the function and how the function
was invoked. Douglas Crockford describes four invocation patterns [1].
When you see the idiom "var self = this;" [2], most likely the
invocation pattern is for a method [3]. In such case, "this" is a
reference to the object containing the method. Such an object may have
other properties which can be accessed via "this" by dot notation:
e.g., this.propertyName.

JavaScript does not have block scoping, it has function scoping [4].
A variable declared with a var statement (anywhere) within a function
has scope within that function and within any (inner) functions
declared within that (outer) function. The inner function's accessing
of the value of the outer functions variable is a "closure." While
quite powerful, their use can sometimes bear gotchas, still, they are
immensely useful [5].

In a simple (illustrative, not useful) example:

var foo = function (k) {
var i, bar;
i = 3;
bar = function (j) {
i = i + 1;
return i + j;
}
return bar(k);
}

Inner function bar is lexically scoped within outer function foo.
Inner function bar can refer to outer function foo's variables (and
arguments). Inner function bar has access to foo's variable "i" by
closure. Any invocation of bar will use the *current* value of i (not
the initially lexically declared value; such mutation of variables
accessed by closure is often a source of gotchas with callback
functions).

btw: in this simple example, "k" is also accessible to bar, and so
doesn't need to be passed in:

var foo = function (k) {
var i, bar;
i = 3;
bar = function () {
i = i + 1;
return i + k;
}
return bar();
}


Now, consider the case where you have a method of an object that has
some properties, and that the method has an inner function which wants
to access the value of a property (again, a highly contrived example):

var o = {
i: 3,
bar: function (k) {
var bar;
bar = function () {
i = i + 1;
return i + k;
}
return bar();
}
}

This is created with the expectation that we can invoke:
o.bar(n); // where n is some numeric value

The problem with the above code is that bar has not declared "i" nor
is there any variable "i" in its scope chain (i.e., method bar doesn't
declare "i" either) [6].

At first blush you may say, "ah, but 'this' in foo refers to the
object" and try:

var o = {
i: 3,
bar: function (k) {
var bar;
console.log("i = " + this.i);
bar = function () {
var i = this.i; // gain local access to the property
i = i + 1;
return i + k;
}
return bar();
}
}

But this doesn't work (double entendre intended).

Presuming that bar is invoked as a method of object o, "this" within
foo does provide access to object o's properties.

However, function bar is invoked by the function invocation pattern,
and within it, "this" is set to the global context, *not* the object.

So, to make the above concept work, we can create a closure to provide
access to the object:

var o = {
i: 3,
bar: function (k) {
var bar,
self = this;
bar = function () {
self.i = self.i + 1;
return self.i + k;
}
return bar();
}
}

In the above, the variable "self" is assigned a value that is a
reference to the object. Unless "self" is mutated, it remains a
reference to the object.

More practical use cases involve callbacks and (often, anonymous)
functions:

var o = {
i: 3,
bar: function (k) {
var bar,
self = this;

someAsyncFunction( arg, function (callbackArg) {
// here, "this" is a reference to the global context
// object o properties can be accessed via the "self"
closure, e.g.:
self.i = self.i + 1;
});
}
}

Idiomatically, you may also see "var that = this" and "var me =
this". Personally, I now avoid "self" because, alas, many Browsers
define a global "self" variable, and so I have had bugs caused by not
declaring "var self = this" when I needed it, yet "self" was defined
(arggh).

Note: I have typed all this in and have *not* executed the code, so
use at your own risk (lol).

1. "JavaScript: The Good Parts", http://oreilly.com/catalog/9780596517748
2. Since I minify most of my JS code, I am diligent about including
semicolons.
3. a "method" is a function that is a property of an object.
4. I am appalled by how much JS code I see posted in which coders use
var statements in a way that implies they believe there is block
scope.
5. Clsoures are a good way of creating private object members: see
Stoyan Stefanov "JavaScript Patterns".
6. Granted, there may be a global variable -- but that would be
horrific programming practice.

Ryan Gahl

unread,
Oct 27, 2010, 9:50:49 AM10/27/10
to nod...@googlegroups.com
I like semicolons;





Tim Caswell

unread,
Oct 27, 2010, 11:40:58 AM10/27/10
to nod...@googlegroups.com
@Ryan Gahl, I know you're trying to reduce unnecessary bike-shedding and some of these threads probably annoy you, but it's not the same thing.  The thread about OO styles is very informative to many people new to javascript, and the OO style you use does have a real impact on both the readability AND the runtime behavior of your code.  In this thread, while what you name the "self" or "me" variable has little consequence, the technique of using it is very powerful and often required for a lot of use cases and styles.  Instead of saying this conversation is meaningless help steer it toward the important points, like what does "this" mean in JavaScript, why are closures important, and especially why does this matter to a node.js programmer.

@Dominic Like others have said, the purpose of "var self = this" is to store a reference to the old "this" value since it will always be overwritten in an inner function scope.  It's a simple use of closures.  It's very important to me that people have a sound understanding of these concepts and so I have written quite a bit about it.





"this" is a funny thing in JavaScript, it has nothing to do with class object instances or methods or anything to do with "self" and "this" in other classical OO languages.  It's controlled 100% by how the function is called.  Having a good understand of both what determines the value of "this" in a function body and what variables are available in the closures are both essential to writing event based systems in JavaScript.  "var self = this" is a simple technique where you're bridging a value from the "this" scope to the closure scope via a local variable.

Ryan Gahl

unread,
Oct 27, 2010, 11:48:45 AM10/27/10
to nod...@googlegroups.com

On Wed, Oct 27, 2010 at 10:40 AM, Tim Caswell <t...@creationix.com> wrote:
@Ryan Gahl, I know you're trying to reduce unnecessary bike-shedding and some of these threads probably annoy you, but it's not the same thing.  The thread about OO styles is very informative to many people new to javascript, and the OO style you use does have a real impact on both the readability AND the runtime behavior of your code.  In this thread, while what you name the "self" or "me" variable has little consequence, the technique of using it is very powerful and often required for a lot of use cases and styles.  Instead of saying this conversation is meaningless help steer it toward the important points, like what does "this" mean in JavaScript, why are closures important, and especially why does this matter to a node.js programmer.


I hear what you're saying. I just feel like the question has been answered, and continuing to debate things like "just don't use 'new' and that gets around having to capture scope"... "use .bind() instead because I find it more readable"... etc amounts to the same ultimate level of value as a debate over semicolons or comma first styles. That said, my little semicolons comments are to taken only as tongue in cheek. Obviously if people find it worth their while to engage in such discussions beyond the point of having answered the OPs question, I have little power to stop it. Don't mind me.

Joe Developer

unread,
Oct 27, 2010, 11:56:44 AM10/27/10
to nod...@googlegroups.com
The thing is that discussions like these can clear up misapprehensions and increase the competence of the people who ultimately contribute to the node ecology. People shouldn't fear to ask questions lest they be sniped by a douche with a penchant for semicolons; That node performance test thread? Same thing. I did a similar thing in the macOS kernel panic thread but it was atleast marginally funny (and I did feel like a douche for doing it).  

Filipe La Ruina

unread,
Oct 27, 2010, 9:49:37 AM10/27/10
to nod...@googlegroups.com
Congratulations Zhami, that's now in my top explanations about scopes in JS and the this problem (that's not a problem at all)

Filipe La Ruina
Web Developer & Programmer
http://www.google.com/profiles/filaruina


Ryan Gahl

unread,
Oct 27, 2010, 12:47:15 PM10/27/10
to nod...@googlegroups.com

On Wed, Oct 27, 2010 at 10:56 AM, Joe Developer <joe.d.d...@gmail.com> wrote:
The thing is that discussions like these can clear up misapprehensions and increase the competence of the people who ultimately contribute to the node ecology. People shouldn't fear to ask questions lest they be sniped by a douche with a penchant for semicolons; That node performance test thread? Same thing. I did a similar thing in the macOS kernel panic thread but it was atleast marginally funny (and I did feel like a douche for doing it).  


oh jeez, you again. good job on the name calling, guy. a douche? really? wow.

I explained I was merely making a tongue in cheek reference to everyone's favorite topic; explained rather simply that I just felt the question had been answered [felt like the conversation was moving towards either redundancy, or opinions on which ways are superior]; said don't mind me ['I'm just being goofy' was supposed to be infered]. I don't think you bringing out the name calling was necessary. But OK, I'm a douche. 

var me = douche; //really?

Joe Developer

unread,
Oct 27, 2010, 1:04:01 PM10/27/10
to nod...@googlegroups.com
I don't know that you are a douche, but I do get the distinct impression that with the "I like semicolons" thing your actions are indistinguishable from those of a douche. What I perhaps should have said is that you seem to be conspicuously unaware of your own limitations, and too quick to draw attention to where you believe to hold knowledge. There is nothing particularly unusual about that and I am sure you are doing fine, I just think that it would be better to ignore or summarize discussions where you feel all the ground has been covered. Filipe and others may never had had the benefit of Zhamis summary if you had in fact managed to stifle discussion. 

We have quite an inflow of programmers who may never have used javascript before or at least not in a structured fashion, as a community we would do ourselves a disservice to not get them up to speed as quickly and congenially as possible. Apologies for being blunt. 

http://groups.google.com/group/comp.lang.javascript/topics is an excellent place to scratch the snipe itch.

Isaac Schlueter

unread,
Oct 27, 2010, 1:44:35 PM10/27/10
to nod...@googlegroups.com
If you guys are gonna flirt, could you do it on a different mailing list?

Thanks :)

--i

Jorge

unread,
Oct 27, 2010, 2:19:39 PM10/27/10
to nod...@googlegroups.com
On 27/10/2010, at 17:40, Tim Caswell wrote:

> @Ryan Gahl, I know you're trying to reduce unnecessary bike-shedding and some of these threads probably annoy you, but it's not the same thing. The thread about OO styles is very informative to many people new to javascript, and the OO style you use does have a real impact on both the readability AND the runtime behavior of your code. In this thread, while what you name the "self" or "me" variable has little consequence, the technique of using it is very powerful and often required for a lot of use cases and styles. Instead of saying this conversation is meaningless help steer it toward the important points, like what does "this" mean in JavaScript, why are closures important, and especially why does this matter to a node.js programmer.
>
> @Dominic Like others have said, the purpose of "var self = this" is to store a reference to the old "this" value since it will always be overwritten in an inner function scope. It's a simple use of closures. It's very important to me that people have a sound understanding of these concepts and so I have written quite a bit about it.
>
> http://howtonode.org/what-is-this
>
> http://howtonode.org/why-use-closure
>
> http://howtonode.org/object-graphs
>
> http://howtonode.org/object-graphs-2
>
> "this" is a funny thing in JavaScript, it has nothing to do with class object instances or methods or anything to do with "self" and "this" in other classical OO languages. It's controlled 100% by how the function is called. Having a good understand of both what determines the value of "this" in a function body and what variables are available in the closures are both essential to writing event based systems in JavaScript. "var self = this" is a simple technique where you're bridging a value from the "this" scope to the closure scope via a local variable.

I save this in that, me self :-)

Cheers,

P.S. ES5 attempts to fix some of this flaws (11.2.3 Function Calls).
--
Jorge.

Charlie Robbins

unread,
Oct 27, 2010, 3:02:26 PM10/27/10
to nod...@googlegroups.com
While I agree with the sentiment, and I agree with the fact that the concept does not translate directly. It does translate sometimes:

var AnObject = function () {}

AnObject.prototype.aFunction = function () {
  var self = this; // self really is the same as ruby, it's the instance of the object
  someAsyncLib.doSomethingAsync(function () {
    self.doSomethingLater();
  });
}

That's when I use it. I might misuse self elsewhere, but I agree that it should be named appropriately. But you know what they say...

Charlie

Robert Kieffer

unread,
Oct 28, 2010, 8:37:45 AM10/28/10
to nodejs
No, that's an endorsement for "var self = this;", not "self = this;"

It's easy to forget that 'var' keyword, as you generously demonstrate,
which leads to important (and undesirable) behavior changes.

And even when things are done correctly, this practice casts doubt on
what each 'self' reference in the code refers to. Is it the window or
something else? The only way to know for sure is to painstakingly
read back through all the closure contexts to see if there's a "var
self = ..." assignment somewhere. It's a pain in the ass.

So, no, the one specific case where this works w/out issue (and is
completely unnecessary anyways) is hardly an endorsement.

- rwk

Jorge

unread,
Oct 28, 2010, 8:46:00 AM10/28/10
to nod...@googlegroups.com
On 28/10/2010, at 14:37, Robert Kieffer wrote:
> On Oct 27, 6:07 am, Micheil Smith <mich...@brandedcode.com> wrote:
>> Robert:
>>
>> In this case it doesn't matter, window.self == this in global scope,
>> which in turn this == window in global scope. See:
>>
>> > self
>> DOMWindow
>> > this
>> DOMWindow
>> > this == window
>> true
>> > this == window.self
>> true
>>
>> I'd see that as an endorsement for self = this;
>>

> No, that's an endorsement for "var self = this;", not "self = this;"


>
> It's easy to forget that 'var' keyword, as you generously demonstrate,
> which leads to important (and undesirable) behavior changes.
>
> And even when things are done correctly, this practice casts doubt on
> what each 'self' reference in the code refers to. Is it the window or
> something else? The only way to know for sure is to painstakingly
> read back through all the closure contexts to see if there's a "var
> self = ..." assignment somewhere. It's a pain in the ass.
>
> So, no, the one specific case where this works w/out issue (and is
> completely unnecessary anyways) is hardly an endorsement.

I agree with Robert.

I don't use 'self', I use 'that', and every JS programmer knows what a 'that' means.
--
Jorge.

Micheil Smith

unread,
Oct 28, 2010, 8:51:17 AM10/28/10
to nod...@googlegroups.com
Robert:

When writing something like that in an english sentence, it's perfectly fine to
leave off var imho. Seriously, deadhorses anyone?

– Micheil

Ryan Gahl

unread,
Oct 28, 2010, 9:53:33 AM10/28/10
to nod...@googlegroups.com

On Thu, Oct 28, 2010 at 7:51 AM, Micheil Smith <mic...@brandedcode.com> wrote:
Seriously, deadhorses anyone?


All over the place, and probably some dead unicorns too. 

Here... use this...

var me = self = that = foo = _this = thisAndThat = (function(outerThis) { return outerThis; })(this);

(don't forget the semicolon)


Robert Kieffer

unread,
Oct 28, 2010, 1:53:54 PM10/28/10
to nodejs
On Oct 28, 6:53 am, Ryan Gahl <ryan.g...@gmail.com> wrote:
> On Thu, Oct 28, 2010 at 7:51 AM, Micheil Smith <mich...@brandedcode.com>wrote:
>
> > Seriously, deadhorses anyone?
>
> All over the place, and probably some dead unicorns too.
>
> Here... use this...
>
> var me = self = that = foo = _this = thisAndThat = (function(outerThis) {
> return outerThis; })(this);
>
> (don't forget the semicolon)

I'm really hoping the missing "var self, that, foo, _this,
thisAndThat;" line to scope those vars locally was just fabulous humor
on your part, cause otherwise you're making this way too easy. :-)

>>> self
Window www.google.com
>>> (function () {var me = self = that = foo = _this = thisAndThat = 'abc';})()
>>> self
"abc"

Ryan Gahl

unread,
Oct 28, 2010, 2:29:14 PM10/28/10
to nod...@googlegroups.com
On Thu, Oct 28, 2010 at 12:53 PM, Robert Kieffer <bro...@gmail.com> wrote:
I'm really hoping the missing "var self, that, foo, _this,
thisAndThat;" line to scope those vars locally was just fabulous humor
on your part, cause otherwise you're making this way too easy. :-)


You just killed another unicorn

:P

Stephen Belanger

unread,
Oct 28, 2010, 2:33:20 PM10/28/10
to nod...@googlegroups.com
Charlie!

--

Isaac Schlueter

unread,
Oct 28, 2010, 2:49:32 PM10/28/10
to nod...@googlegroups.com
> var me = self = that = foo...

var a = b = 1
creates a var "a" and a *global* "b".

--i

Ryan Gahl

unread,
Oct 28, 2010, 3:01:15 PM10/28/10
to nod...@googlegroups.com

On Thu, Oct 28, 2010 at 1:49 PM, Isaac Schlueter <i...@izs.me> wrote:
var a = b = 1
creates a var "a" and a *global* "b".


LOL

don't forget that it also creates a global "1"

Ryan Gahl

unread,
Oct 28, 2010, 3:02:07 PM10/28/10
to nod...@googlegroups.com
I really hope you get my and Micheil's point and are just playing along :)

Micheil Smith

unread,
Oct 28, 2010, 3:19:59 PM10/28/10
to nod...@googlegroups.com
Ryan:

I'm not playing along, I'm just saying it's getting kinda silly now, it's been
explain and everyone has gone into almost anal detail. There's no need
to keep bickering about it, really.

Yours,
Micheil Smith
--
BrandedCode.com

Isaac Schlueter

unread,
Oct 28, 2010, 3:20:58 PM10/28/10
to nod...@googlegroups.com
Are we bickering? I thought we were making friends and influencing people.

Ryan Gahl

unread,
Oct 28, 2010, 3:25:49 PM10/28/10
to nod...@googlegroups.com
That's what I was saying way back in the good old days of this thread.

just tried adding a little humor to the point.

Ryan Gahl

unread,
Oct 28, 2010, 3:29:43 PM10/28/10
to nod...@googlegroups.com
I thought we were making people and influencing friends

#reddit_style

Stephen Belanger

unread,
Oct 28, 2010, 4:01:14 PM10/28/10
to nod...@googlegroups.com
The Internet.

Serious business.

Robert Kieffer

unread,
Oct 28, 2010, 8:38:47 PM10/28/10
to nodejs
Having vanquished the dastardly var-ments, /broofa gets on his dead
unicorn and rides off into the sunset

-- Fin --

resopoll

unread,
Oct 29, 2010, 1:10:04 AM10/29/10
to nodejs
I use self as well, habit from python, but window.self seems to
endorse using self for js.

Marak Squires

unread,
Oct 29, 2010, 1:11:55 AM10/29/10
to nod...@googlegroups.com
You can't touch this.

On Fri, Oct 29, 2010 at 1:10 AM, resopoll <weix...@gmail.com> wrote:
I use self as well, habit from python, but window.self seems to
endorse using self for js.

dipti seni

unread,
Oct 29, 2010, 12:25:05 AM10/29/10
to nod...@googlegroups.com

www.ksrista.com
           search your life partner

Tane Piper

unread,
Oct 29, 2010, 2:30:26 AM10/29/10
to nod...@googlegroups.com
Wow, derailed by spam.

Those poor horses, unicorns, narwhals and fluffy kittens that died in
the making of this thread.

On Fri, Oct 29, 2010 at 5:25 AM, dipti seni <dipp...@gmail.com> wrote:
>
> www.ksrista.com
>            search your life partner
>

dipti seni

unread,
Oct 29, 2010, 1:13:00 AM10/29/10
to nod...@googlegroups.com, weix...@gmail.com

cbmeeks

unread,
Nov 10, 2010, 8:06:26 AM11/10/10
to nodejs
OMG...I just had nightmares of my VB.NET days. lol



On Oct 26, 6:18 pm, Ryan Gahl <ryan.g...@gmail.com> wrote:
> var me = this; //FTW
>
> 'me' is 50% less typing than 'self'. so obvious that it's better.
>
> pffffffshhhhhh.
>
> :P
>
> On Tue, Oct 26, 2010 at 6:10 PM, Marak Squires <marak.squi...@gmail.com>wrote:
>
>
>
>
>
>
>
> > It's a way of maintaining the scope of "this" inside another scope.
>
> > "self" is arbitrary, you could call it "foo" if you wanted.
>
> > On Tue, Oct 26, 2010 at 7:07 PM, Keith Pitt <m...@keithpitt.com> wrote:
>
> >> You usually do that when you want to reference scope of another object.
> >> For example:
>
> >> var functionX = function() {
> >>   var self = this;
> >>   var functionY = function(y) {
> >>     // If we call "this" in here, we get a reference to functionY,
> >>     // but if we call "self" (defined earlier), we get a reference to
> >>     // function X.
> >>   }
> >> }
>
> >> Does that make sense?
>
> >> *Keith Pitt*
> >> Web:http://www.keithpitt.com
> >> Twitter: @keithpitt
> >> Skype: keithpitt
> >> Phone: +61 432 713 987
>
> >> On Wed, Oct 27, 2010 at 9:33 AM, Dominic Tarr <dominic.t...@gmail.com>wrote:
>
> >>> what is the purpose of
>
> >>> self = this
>
> >>> I've seen it a bunch of times now, but not 100% sure what it's for.
>
> >>> is it so that functions in a object retain access to the object's
> >>> prototype/instance and would 'this' point to the prototype object of a
> >>> function if it is not initialized with new?
>
> >>> --
> >>> You received this message because you are subscribed to the Google Groups
> >>> "nodejs" group.
> >>> To post to this group, send email to nod...@googlegroups.com.
> >>> To unsubscribe from this group, send email to
> >>> nodejs+un...@googlegroups.com<nodejs%2Bunsu...@googlegroups.com>
> >>> .
> >>> For more options, visit this group at
> >>>http://groups.google.com/group/nodejs?hl=en.
>
> >>  --
> >> You received this message because you are subscribed to the Google Groups
> >> "nodejs" group.
> >> To post to this group, send email to nod...@googlegroups.com.
> >> To unsubscribe from this group, send email to
> >> nodejs+un...@googlegroups.com<nodejs%2Bunsu...@googlegroups.com>
> >> .
> >> For more options, visit this group at
> >>http://groups.google.com/group/nodejs?hl=en.
>
> >  --
> > You received this message because you are subscribed to the Google Groups
> > "nodejs" group.
> > To post to this group, send email to nod...@googlegroups.com.
> > To unsubscribe from this group, send email to
> > nodejs+un...@googlegroups.com<nodejs%2Bunsu...@googlegroups.com>
> > .
Reply all
Reply to author
Forward
0 new messages