2

抱歉,如果这个问题已经得到解答,但我无法搜索它......我认为这是一个很难搜索的东西!

说我有这个:

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引用我想要的东西!

4

5 回答 5

2

在这里结合其他两个答案,这样你就不必重写你的 meth 函数,我会这样做:

    var me = this;
    thing.meth = function() {
        MyPrototype.meth.apply(me, arguments);
    };
于 2009-07-27T22:04:52.403 回答
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);
    }
}
于 2009-07-27T21:57:04.573 回答
0

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

var self = this;

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

(我认为很多对此的答案或多或少都在说同样的事情。)

于 2009-07-27T22:06:42.790 回答
-1

怎么样:

thing.meth.call(this);

或者

thing.meth.apply(this);

(唯一的区别在于参数的传递方式,在这种情况下并不重要。)

于 2009-07-27T21:38:31.177 回答
-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);
    }
}
于 2009-07-27T21:56:09.223 回答