Javascript继承问题
使用以下代码,我似乎无法正确覆盖类方法Javascript继承问题,javascript,inheritance,Javascript,Inheritance,使用以下代码,我似乎无法正确覆盖类方法 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 = co
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
上使用的原型与core
上使用的原型相同,因此当您从任何类调用.output()
时,core.prototype.output
上的函数是sub2
版本,因为它是最后定义的版本。请记住,对象指定是通过引用进行的
要复制常见的对象,请执行以下操作:
sub2.prototype = new core();
sub2.prototype.core = core;
或者-如果希望避免调用构造函数,可以使用jQuery的$.extend(sub1.prototype,core.prototype)代码>复制核心原型。如果没有jQuery,则大致相同:
sub2.prototype = {};
for (var method in core.prototype) sub2.prototype[method] = core.prototype[method];
sub2.prototype.constructor = core;
sub2.prototype.core = core;
没有为此使用JQuery(故意避免将代码绑定到JS框架),但下面的示例工作得非常好。谢谢你。