views:

64

answers:

5

We have discussion with our team about next: What correct name should have variable which will be alias for "this" in anonymous function. Simple example:

var SomeConstructor = function() {

    this.someProperty = 'bingo';

    this.someMethod = function() {

        var myObjectAlias = this;

        $('a').click(function() {
            alert( myObjectAlias.someProperty );                  
        });

    }
}

So my question is - What correct name should have variable "myObjectAlias"? Or what used in your code for example?

+4  A: 

Hey,

You see a lot of in code samples.

var that = this;

$('a').click(function() {
         alert( that.someProperty );                  
});

To do that; it really doesn't matter, whatever you want.

Brian
+2  A: 

I tend to use self in these cases, or _self to be explicit, has the meaning of this without the conflicts, keeping things simple and intuitive, at least for me.

For example:

self.property
self.doSomething()
if(self.hasPickles) {
  self.eat();
}

It's all a matter of preference of course, but the majority of JS developers that I've talked to find this naming style pretty intuitive, that's not to say the overall majority does, but that doesn't matter does it? Do what works for your team :)

Nick Craver
A: 

I think sometimes it's good to use meaningful names, like "form" or "container" or whatever. In short little blocks of code is not that big a deal, but in complicated initializations for forms or dialogs there tends to be several different "interesting" objects buzzing around.

Pointy
A: 

I prefer to use self for reasons Nick Craver described.

Viktor Molokostov
A: 

on a tangent: consider using prototypes for your constructor:

var SomeConstructor = function() {}
SomeConstructor.prototype = {

    someProperty: 'bingo',

    someMethod: function() {   
        var self = this;    
        $('a').click(function() {
            alert( self.someProperty );                  
        });    
    }
}

The someProperty and someMethod properties can be shared among all instances, so they work fine this way. Whenever you need separate values for each instance, you should put those in the constructor itself.

Jason S
@Jason S: thanks for your comment!I know about prototype, but my question not about that.From your example I see that your choice for alias is "self".
Roman