In my project I am using JavaScript prototypes to achieve inheritance. I have a super type (like car) and many subtypes (audi/mercedes/...). Every car brand is using 'Horn' which is a quite huge type and should not be duplicated. One method of this type should be overwritten by each car brand, but should only persist in the scope of the specific subtype. Is this possible without creating a Horn subtype for every car subtype? Thank you!
http://codepen.io/trek7/pen/QGYaBW
function Horn() {
this.level = '123dB';
}
Horn.prototype.doTutut = function() {
return "Düdelüüüü!";
};
/********************************************/
function Car() {
this.horn = new Horn();
}
Car.prototype.honk = function() {
return this.horn.doTutut();
};
/********************************************/
Mercedes.prototype = new Car();
function Mercedes() {
this.color = 'blue';
}
Mercedes.prototype.drive = function() {
return "...BrumBrum...";
};
/********************************************/
Audi.prototype = new Car();
function Audi() {
this.color = 'red';
/* BAD Overwrite, but how can I achieve this functionality
without creating another Horn subtype? */
Horn.prototype.doTutut = function() {
return "Tütütütütü!";
};
}
Audi.prototype.honk = function() {
return this.horn.doTutut();
};
/********************************************/
var car = new Car();
car.honk(); // Düdelüüüü! - Right!
var mercedes = new Mercedes();
mercedes.honk(); // Düdelüüüü! - Right!
var audi = new Audi();
audi.honk(); // Tütütütütü! - Right!
mercedes.honk(); // Tütütütütü! - Wrong!