我对如何通过原型继承实现代码重用有点困惑。我正在关注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
. 我想我应该做差分继承,但不知道怎么做?有什么帮助吗?