我已经有 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/