在我的小脑中,我无法解释如何正确引用对象原型中的方法:
function A(){}
A.prototype.action = function(){}
A.prototype.dict = { action: this.action } // Mistake here.
var a = new A();
a.dict.action(); // -> undefined, but I expect a call of 'A.prototype.action' or other function if I override it in 'a'
答案 0 :(得分:0)
您还没有真正解释为什么需要此功能,但以下内容可帮助您避免出现的错误。无论这是否是好的做法,我都会留给你研究。
function A() {
var self = this;
this.dict = {
action: function() {
// by default, A.dict.action calls A.action
return self.action();
}
};
}
// Define A.action
A.prototype.action = function() {
console.log('prototype');
};
// Let's test it out
var a = new A();
a.dict.action(); // prints 'prototype'
// Override it on instance a
a.dict.action = function() {
console.log('overridden');
};
a.dict.action(); // prints 'overridden'
// Let's create a new instance of A: b
var b = new A();
b.dict.action(); // prints 'prototpye'