我已经编程了20多年,但最近转向使用JavaScript。尽管花费了数小时的时间来拖网,但这个便士还没有用原型继承方法。使用原型进行JavaScript继承
在下面的简化代码中,我试图从Synthesizer'class'继承'roland'类的'name'属性,但我似乎能够访问它的唯一方法是使用'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>');
退房http://javascript.crockford.com/prototypal.html我认为它会变得更加清晰。 – PM5544
感谢您的回答,链接内容丰富。 – AndyC