我似乎无法正确覆盖类方法,使用以下代码...
function core() {
console.log( "CORE CONSTRUCTOR CALLED" );
}
core.prototype.output = function() {
return 'CORE';
}
function sub1() {
console.log( "SUB 1 CONSTRUCTOR CALLED" );
this.core();
}
sub1.prototype = core.prototype;
sub1.prototype.constructor = sub1;
sub1.prototype.core = core;
sub1.prototype.output = function() {
return 'SUB 1';
}
function sub2() {
console.log( "SUB 2 CONSTRUCTOR CALLED" );
this.core();
}
sub2.prototype = core.prototype;
sub2.prototype.constructor = sub2;
sub2.prototype.core = core;
sub2.prototype.output = function() {
return 'SUB 2';
}
var oCore = new core();
var oSub1 = new sub1();
var oSub2 = new sub2();
console.log( oCore.output() );
console.log( oSub1.output() );
console.log( oSub2.output() );
...我得到以下输出...
CORE CONSTRUCTOR CALLED
SUB 1 CONSTRUCTOR CALLED
CORE CONSTRUCTOR CALLED
SUB 2 CONSTRUCTOR CALLED
CORE CONSTRUCTOR CALLED
SUB 2
SUB 2
SUB 2
我做错了什么?
最佳答案
问题是...当您发布行时:
sub2.prototype = core.prototype;
您在 sub2
上使用相同的原型(prototype)作为core
, 因此当你调用 .output()
来自 任何 类,core.prototype.output
处的函数是 sub2
版本,因为它是最后一个定义的。请记住,对象分配是通过引用发生的。
要复制您经常看到的对象:
sub2.prototype = new core();
sub2.prototype.core = core;
或者 - 如果您想避免调用构造函数,您可以使用 jQuery 的 $.extend(sub1.prototype, core.prototype);
复制核心原型(prototype)。如果您没有 jQuery,这大致相同:
sub2.prototype = {};
for (var method in core.prototype) sub2.prototype[method] = core.prototype[method];
sub2.prototype.constructor = core;
sub2.prototype.core = core;
关于Javascript继承问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3562000/