I'm not sure there is any measurable benefit so to speak. Someone with
more knowledge on the subject can correct me if i'm wrong.

For me, it's a stylistic/readability issue. I always use a local
variable for the base object. A small example:

var someObject = {
    property: "value"
};

someObject.prototype.initialize = function() {
    // init object properties, cache your dom elements, bind your
event handlers, etc
    var self = this;
    self.bindEventHandlers();
};

someObject.prototype.bindEventHandlers = function() {
    // storing object as local variable helps here, because as scope
changes in the event handlers, we can still reference our base object
easily
    var self = this;

    $("#someID").bind("click", function(event) {
        // "this" refers to the DOM element with id "someID" within
the scope of this handler
        // so we can use self to refer to the base object
        self.handleEvent(this, event);
    });
};

So for me, it is easier to reference your base object when the scope
has changed when using a local variable like "self" (you can use
whatever you want of course), and I think it is more readable than
"this" because we aren't always sure to what "this" refers. Hope this
small example makes sense.

Others could disagree, but this is how i like to write my code. I'm
interested in what others do in practice :) I'm always looking to
learn!


On Dec 30, 5:48 am, Tom Wilson <twilson...@gmail.com> wrote:
> I just finished reading "High Performance JavaScript" and now I'm paying more 
> attention to scope. So my question is: within an object method, is there any 
> benefit to declaring a local variable referencing 'this'? Is that just 
> redundant? What about a local variable referencing a property of 'this' that 
> is itself an object? Like var myLocal = this.someProperty so that you can 
> refer  to myLocal.x, myLocal.y, etc.
>
> Thanks!
>
> --Tom

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/jsmentors@jsmentors.com/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/jsmentors@googlegroups.com/

To unsubscribe from this group, send email to
jsmentors+unsubscr...@googlegroups.com

Reply via email to