Javascript继承问题

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

我做错了什么?

最佳答案

问题是...当您发布行时:

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/

相关文章:

javascript - 使用 getElementById 即时创建网站?

javascript - 即 10 : SCRIPT5: Access is Denied error on anchor click event

javascript - jQuery 语法荧光笔不工作

javascript - Discord.js - 让用户上次事件?

inheritance - F# 4.0 继承引发 FS0073 内部错误 : the mustinline value 'Foo' was not inferred to have a known value

c++ - 了解一个简单的 C++ 类结构

javascript - 非递归代码递归

java - 为什么动态绑定(bind)在这里不适用?

c# - 如果类继承多次可以慢一些吗?

C++ 多重继承和向上转换的智能指针销毁导致 VS 2017 中的堆损坏