使用原型的JavaScript继承

时间:2011-11-20 18:41:16

标签: javascript prototypal-inheritance

我已经编程超过20年,但最近转向JavaScript。尽管花了几个小时在网上搜索,但是使用原型继承方法还没有下降。

在下面的简化代码中,我试图将Synthesizer'class'中的'name'属性继承到Roland'类',但我似乎能够访问它的唯一方法是使用'Synth2'。 prototype.name'而不是'Synth2.name'(返回undefined)。我想让这个方法有效,以便我可以使用'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>');

谢谢你们! (现在通过调用超级类来更新)...

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>');

2 个答案:

答案 0 :(得分:1)

我相信你必须设置构造函数prototype,如下所示:

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

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

Roland.prototype = new Synthesizer();

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

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

答案 1 :(得分:1)

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

例如:

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