开发者

Javascript: is using t_this inside anonymous functions considered harmful?

I've been using:

var t_thi开发者_开发技巧s = this; // Used inside anonymous functions

for quite some time when dealing with anonymous functions inside a 'class' but always with unease as it looks like a code smell. Is this a bad practice? Is there a better alternative?

example:

$("#container").click(function() {
    t_this.doSomething();
});


This is a common practice; there's nothing wrong with it.

However, underscores are not usually used in Javascript identifiers; I would name the variable me or self (or even that)


Not at all, though I usually call it $this (if it's a proper jQuery object) or that, unless I can give it a more descriptive name.


This is the standard way to reference the value of this in an outer scope. Consider, for example:

function output() {
    var t_this = this;
    $("#container").click(function() {
        t_this.doSomething();
    });
}

The value of this inside the click handler will not be the same as the value of this in the outer function. Assigning its value to another variable is exactly the way to solve this problem.


Other than maybe picking a better name, this practice is recommended in lots of situations, and works as a caching mechanism by reducing calls to object lookups outside the current scope. Recommended for more than just this.

For example, if you have an object outside of the current scope like:

var Application = {
    a: {
        b: {
            c: {}
        }
    }
};

You will want to cache that to reduce processing from traversing the object. Instead of:

Application.a.b.c.doSomething();

// later

Application.a.b.c.doSomething();

Cache it, much quicker:

var c = Application.a.b.c;

c.doSomething();

// later

c.doSomething();

In this way, c is only looked up once, as opposed to multiple times.


An alternative is to use proxy.

$("#container").click($.proxy( 
    function() { this.doSomething(); },
    this // you can use any variable here, and it will be called 'this' inside the function
));

This way you pass the context to the inside scope. Not saying it's better, but maybe it smell better for you. I prefer this way.


I don't get it, why you need to alias this instead of using it? I only alias this when I have another nested anonymous function with a different caller. for example:

    $('#container').click(function() {
        // this refer to #container
        this.doThis();

        // alias this
        objPointer = this;

        // call a function on different objects
        $('div.class').click(function(){
            // this now refer to div.class
            this.doElse()

            // objPointer refer to #container
            objPointer.doThis()
        });
    });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜