Javascript继承问题

时间:2010-08-25 00:21:36

标签: 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 = 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

我做错了什么?

1 个答案:

答案 0 :(得分:4)

问题是......当你发出这条线时:

sub2.prototype = core.prototype;

您在sub2上使用SAME原型core,因此当您从 ANY 类中调用.output()时,{{1}处的函数是core.prototype.output版本,因为它是最后定义的版本。请记住,对象分配通过引用发生。

要复制通常会看到的对象:

sub2

或者 - 如果你想避免调用构造函数,你可以使用jQuery的sub2.prototype = new core(); sub2.prototype.core = core; 来复制核心原型。如果你没有jQuery,那就差不多了:

$.extend(sub1.prototype, core.prototype);