JavaScript 使用原型(prototype)继承

标签 javascript prototypal-inheritance

我已经有 20 多年的编程经验,但最近转向了 JavaScript。尽管花了几个小时在网络上搜寻,但原型(prototype)继承方法还没有花上一分钱。

在下面的简化代码中,我试图将“name”属性从合成器“class”继承到Roland“class”,但我似乎能够访问它的唯一方法是使用“Synth2.class”。 prototype.name”而不是“Synth2.name”(返回未定义)。我想让该方法发挥作用,以便我可以使用“Synth2.name”,因为可移植性是一项设计要求。

如果您有任何帮助,我将非常感激。

function Synthesizer(name) {
    this.name = name;
}

function Roland(name) {
    this.prototype = new Synthesizer(name);
}

Synth1 = new Synthesizer("Analogue");
Synth2 = new Roland("Fantom G6");

document.write(Synth1.name + '<br>');
document.write(Synth2.name + '<br>');

谢谢大家! (现在更新为调用父类(super class))...

function Synthesizer(name) {
    this.name = name;

    this.rendersound = function () {

        document.write("applying envelope to " + this.name + "<br>");

    }
}

function Roland(name) {
    Synthesizer.call(this, name);
    this.prototype = Synthesizer;

    this.Synthesizer_rendersound = this.rendersound;
    this.rendersound = function () {

        document.write("applying differential interpolation to " + this.name + "<br>");
        this.Synthesizer_rendersound(this);

    }

}

Synth1 = new Synthesizer("Analogue");
Synth2 = new Roland("Fantom G6");

document.write(Synth1.name + '<br>');
document.write(Synth2.name + '<br>');

document.write('<br>');
Synth1.rendersound();

document.write('<br>');
Synth2.rendersound();

document.write('<br>');
document.write('Synth1.prototype ' + Synth1.prototype + '<br>');
document.write('Synth2.prototype ' + Synth2.prototype + '<br>');

document.write('<br>');
document.write('Synth1.constructor ' + Synth1.constructor + '<br>');
document.write('Synth2.constructor ' + Synth2.constructor + '<br>');

最佳答案

您可以通过多种方式做到这一点。

例如:

var Synthesizer = function(name){
   this.name = name;
}

function Roland(name) {
   Synthesizer.call(this, name); // you call the constructor of Synthesizer 
                                 // and force Synthesizer's this to be Roland's this
}
function clone(obj){
   var ret = {};
   for(var i in obj){ ret[i] = obj[i]; }
   return ret;
}
Roland.prototype = clone(Synthesizer.prototype); // inheritance of public functions

对于 Function.prototype.call :https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Call

关于JavaScript 使用原型(prototype)继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8203735/

相关文章:

javascript - 在NodeJS的 `message`类中未设置 `CustomError`字段的值,该类具有通过函数构造函数的经典继承

javascript - jQuery 数据表 : Individual column searching not working

javascript - 将动态数据传递给路由器链路。

javascript - 页面退出时的 CSS 过渡属性

javascript - React 添加自定义 props 到普通 html 元素

javascript - Object.create 原型(prototype)链

javascript - setTimeout(fn, 0) 和 setTimeout(fn, 1) 有什么区别?

javascript - 为什么 JavaScript ES5 原型(prototype)继承中需要代理类?

javascript类继承自Function类

javascript - 什么时候应该使用自己的命名空间,什么时候应该扩展原生 js 对象?