我对如何通过原型(prototype)继承实现代码重用有点困惑。我正在按照 http://alexsexton.com/?p=51 中的示例进行操作它创建一个Speaker对象并将其与jQuery桥接。
假设我想要一个与示例中的扬声器类似的新扬声器,但现在带有额外的声音文件。我能想到的唯一代码是:
var AnotherSpeaker = Object.create(Speaker);
$.extend(true, AnotherSpeaker, {
init: function(options, elem){
this.options.soundFile = options.soundFile || this.options.soundFile;
Speaker.init.call(this, options, elem);
},
options:{
soundFile: 'abc.wav'
},
_playSound: function(){
//....code to play the sound this.options.soundFile;
},
speak: function(msg){
this._playSound();
Speaker.speak.call(this, msg);
}
});
$.plugin('AnotherSpeaker', AnotherSpeaker); //jquery plugin bridge
但这种方法对我来说实际上听起来相当“经典”。我通过 Speaker.xxx.call
调用“ super ”。我想我应该做差异继承,但不知道如何做?有什么帮助吗?
最佳答案
您已经在进行差异继承(指定 AnotherSpeaker
与 Speaker
的不同之处)。
关于通过call
对Speaker.speak
进行“ super 调用”的问题:是的,这很痛苦。 super 调用是 JavaScript 无法提供太多开箱即用的帮助的领域。根据您正在使用的结构,这可能是最好的方法。
几年前I defined a system使 super 调用既简单又高效。它涉及使用辅助函数来创建构造函数(我在文章中将它们称为类,这是我当时还没有在脑海中进行类到原型(prototype)转换的产物),但除了术语之外,它是实际上是原型(prototype)继承。您可能会发现这很有帮助。
关于javascript - 通过 Javascript 原型(prototype)继承重用代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6827989/