Should I reference 'this' in local variabl

2019-06-28 01:25发布

I often see this in code: var me = this;. Why is that? Is there some performance gain if I reference 'this' in local variable?

8条回答
戒情不戒烟
2楼-- · 2019-06-28 02:05

That is for closure scope. Look at the difference in these two jQuery plugins:

$.fn.blinkClosure = function() {
    var jQueryMonad = this, toggleClass = this.toggleClass;
    setInterval(function() {
        toggleClass.apply(jQueryMonad, ['invisible']);
    }, 500);
};

The problem is with setInterval. When the function in setInterval gets called, it starts a new chain of execution, and this in that chain is bound to window. In the closure example, we keep a reference to the jQuery object we apply the plugin to in the jQueryMonad (or me in your code). This way, we can keep our scope correct in javascript.

$.fn.blink = function() {
    setInterval($.proxy(function() {
        this.toggleClass('invisible');
    }, this), 500);
};

In the second example, jQuery.proxy handles that for you.

This is to solve the issues when javascript binds this at execution time, instead of creation time.

查看更多
Bombasti
3楼-- · 2019-06-28 02:15

IMO it's unusual you'd see that on its own--it's a construct almost always used when there are closures involved to avoid JS's treatment of the this value, evaluated during execution, not declaration.

查看更多
登录 后发表回答