很抱歉,如果已经回答了这个问题,但是我无法找到它......我认为这很难找到!
说我有这个:
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
引用我想要的东西,但是!
答案 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);
}
}