开发者

What is the simplest & shortest way to access outer this from inside callback in javascript?

I know the following code can access outer this.


var o = function() {
    var that = this;
    this.a = 1;
    $('html').click(function() {
        alert(that.a);
    });
}
new o();

But I don't wanna use two variable names(for example, this and that) for the same one object.

And I don't wanna repeatedly write var that = this on every class.

I think the following code which uses _this instead of that is a little bit simpler.


var o = function()开发者_JAVA百科 {
    var _this = this;
    this.a = 1;
    $('html').click(function() {
        alert(_this.a);
    });
}
new o();

But are there other simpler and shorter ways?


I really like Ext's createDelegate function, which let's you set the this value for any function when it is created.

Here is a less functional version of createDelegate that you could include in your page:

Function.prototype.createDelegate = function(thisObj) {
    var method = this;
    return function() {
        return method.apply(thisObj || window, arguments);
    };
}

And here is how you can use it in your example, never setting this to a variable:

var o = function() {
    this.a = 1;
    $('html').click(function() {
        alert(this.a);
    }.createDelegate(this));
}
new o();

The full version of Ext's createDelegate let's you pass in parameters as the second argument, and they can be used instead of, inserted into, or appended to the list of arguments that would regularly be passed into the function you are creating a delegate of


here is some similar code but I believe it is 'safer' than your example, if you create more than 1 instance of 'o' each instance could update the 'a' property

var bar = function() {
        var that = {};
        that.a = 1;
        that.showA = function () {
            $('html').click(function() {
                alert(that.a);
            });
        };
        return that;
}
var instanceOfBar = bar();
instanceOfBar.showA();

I might be off base here, have not had my hands in javascript for a few months, so rusty at the moment

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜