假设我有一个javascript类Library1.B
,它从同一个库中的超类继承methodA
。
假设我想将Library1
克隆到Library2
中,以便制作我自己的版本,并稍微覆盖Library1.B
的继承的methodA
以改进它。天真,我阐述了这样做:Javascript - 在克隆库中重写继承的方法
/* Library 1 */
var Library1 = {};
Library1.A = function() {
console.log("A's constructor called");
};
Library1.A.prototype.methodA = function() {
console.log("methodA called with arguments", arguments);
//heavy computation
};
Library1.B = function() {
Library1.A.call(this);
//Set a few other properties exclusive to B
};
Library1.B.prototype = Object.create(Library1.A.prototype);
/* Library 2 */
var Library2 = Library1;
Library2.B.prototype.methodA = function() {
console.log("Before invoking methodA()");
Library1.B.methodA.apply(this, arguments);
console.log("After invoking methodA()");
};
var o1 = new Library1.B();
o1.methodA(1, 2, 3);
var o2 = new Library2.B();
o2.methodA(4, 5, 6);
(的jsfiddle here)
预计日志上面:
A's constructor called
methodA called with arguments [1, 2, 3]
A's constructor called
Before invoking methodA()
methodA called with arguments [4, 5, 6]
After invoking methodA()
相反,我得到这样的:
A's constructor called
Before invoking methodA()
Uncaught TypeError: Cannot read property 'apply' of undefined
因此很明显, o1
,尽管是用构建的对象0的构造函数(它又调用Library1.A
的构造函数),已经使用Library2
的覆盖的methodA
;它然后在Library1.B.methodA.apply
电话崩溃,我想因为Library1.B
没有它自己的methodA
,而是从Library1.A
继承。
我的意思是,当我写Library1.B.methodA
实际上是“抬头Library1.B
的原型链,直到找到定义methodA
,然后调用它this
这些arguments
”是什么。
什么是实现这一目标的正确方法?
你认为这行做了什么'var Library2 = Library1'? – elclanrs 2014-10-05 12:23:08
我看到你在哪里:我期望'Library2'成为'Library1'的一个*拷贝*,但我想它只是成为对'Library1'的引用,所以在'Library2'上调用的任何东西实际上都会被调用' Library1'?我会尝试编辑小提琴,看看问题是否仍然存在,谢谢你的提高。 – 2014-10-05 12:49:43
好吧,编辑jsFiddle(http://jsfiddle.net/axedre/puposqs5/1/),但仍然没有骰子:与以前一样的错误。 :( – 2014-10-05 12:57:38