JavaScript继承使用原型

JavaScript inheritance using prototype

本文关键字:原型 继承 JavaScript      更新时间:2023-09-26

我已经编程20多年了,但最近才转向JavaScript。尽管花了几个小时在网上搜索,但原型继承方法还没有得到解决。

在下面的简化代码中,我试图将"name"属性从合成器"类"继承到Roland"类",但我似乎能够访问它的唯一方法是使用"Synth2.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>');

谢谢你们了!(现在更新为调用超类)…

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

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

我相信你必须设置构造函数的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>');