在Javascript(和jQuery.extend)中确定“this”

时间:2009-07-27 21:34:48

标签: javascript jquery this

很抱歉,如果已经回答了这个问题,但是我无法找到它......我认为这很难找到!

说我有这个:

var MyPrototype = function() { this.init(); }
$.extend(MyPrototype.prototype, {
    a: 5,
    init: function() {
        var thing = new SomeOtherClass();
        thing.meth = this.meth;
        // thing.meth() is called somewhere within thing;
    },
    meth: function() {
        alert(this.a);
    }
}

基本上,我正在处理另一个使用自己的方法作为回调的类,例如我希望用我自己的功能覆盖它们。但是我需要保留this的适当范围(从SomeOtherClass我唯一关心的是传递回调的内容;状态中没有任何内容)。

正如您可能想象的那样,这不起作用,因为thing没有a属性!我不熟悉Javascript范围的复杂性,知道如何让this引用我想要的东西,但是!

5 个答案:

答案 0 :(得分:2)

在这里结合其他两个答案,这样你就不必重写你的甲基化功能,我会这样做:

    var me = this;
    thing.meth = function() {
        MyPrototype.meth.apply(me, arguments);
    };

答案 1 :(得分:1)

由于你无法控制它的调用方式,你可以试试这个:

var MyPrototype = function() { this.init(); }
$.extend(MyPrototype.prototype, {
    a: 5,
    init: function() {
        var thing = new SomeOtherClass();

        // Create an aliad for this
        var that = this;
        thing.meth = function() {
            // You can always access the object using it's "that" alias
            alert(that.a);
        };
    }
}

或者...

var MyPrototype = function() { this.init(); }
$.extend(MyPrototype.prototype, {
    a: 5,
    init: function() {
        var thing = new SomeOtherClass();

        // Create an aliad for this
        var that = this;
        thing.meth = function() {
            // You can always access the object using it's "that" alias
            that.meth();
        };
    },
    meth: {
        alert(this.a);
    }
}

答案 2 :(得分:0)

在代码示例开始之前,添加以下行:

var self = this;

然后将代码中“this”的所有用法替换为“self”。

(我认为对此的一些答案或多或少都是相同的。)

答案 3 :(得分:-1)

怎么样:

thing.meth.call(this);

thing.meth.apply(this);

(唯一的区别在于如何传递参数,在这种情况下无关紧要。)

答案 4 :(得分:-1)

你可以这样做吗?

var MyPrototype = function() { this.init(); }
$.extend(MyPrototype.prototype, {
    a: 5,
    init: function() {
        var thing = new SomeOtherClass();
        var self = this;
        thing.meth = function(){this.meth.apply(self)};
        // thing.meth() is called somewhere within thing;
    },
    meth: function() {
        alert(this.a);
    }
}