问题
I'm a bit confused with how to achieve code re-use with the prototypal inheritance. I'm following the example at http://alexsexton.com/?p=51 where it create a Speaker object and bridge it with jQuery.
Say I want a new speaker that is similar to the one in example, but now with a extra sound file. The only code I can think of is like:
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
But this approach actually sounds quite 'classical' to me. I'm calling the 'super' through Speaker.xxx.call
. I think I'm suppose to do differential inheritance but can't figure out how? Any help?
回答1:
You're already doing differential inheritance (specifying what's different about AnotherSpeaker
as opposed to Speaker
).
Regarding your issue with the "supercall" to Speaker.speak
via call
: Yes, that is a pain. Supercalls are an area where JavaScript doesn't help you very much out-of-the box. With the structure you're using, that's probably going to be the best way to do it.
A couple of years ago I defined a system for making supercalls both easy and efficient. It involves using a helper function to create the constructor functions (I call them classes in the article, an artefact of my not having made the class-to-prototype transition in my head yet at the time), but aside from the terminology it is actually prototypical inheritance. You may find that helpful.
回答2:
When object orientation was new, it was common to think that inheritance is good for code reuse. Newer wisdom is that inheritance creates high coupling, and that reuse is often better enabled with aggregation instead of inheritance.
I couldn't reach the article you linked to, so I can't be more specific to your case.
来源:https://stackoverflow.com/questions/6827989/code-re-use-through-javascript-prototypal-inheritance