The instance properties of the base class are inherited at the point where the derived class constructor calls the base class constructor. At this point, all the instance properties of the base class which need to be inherited privately can be stored as local variables inside the constructor of the derived class and subsequently deleted from the instance of the derived class.
This technique would obviously not work for properties inherited off the prototype of the base class. This, however, served my use case, and hence I'm sharing it here.
In the example below, the derived class ChocolateCake
privately inherits the member setBakingTemperature
from the base class Cake
.
function Cake() {
var bakingTemperature = 250;
this.setBakingTemperature = function(temperature) {
bakingTemperature = Math.min(temperature, 400);
}
this.getBakingTemperature = function() {
return bakingTemperature;
}
}
Cake.prototype.bake = function() {
console.log("Baking the cake at " + this.getBakingTemperature() + " °C");
}
function ChocolateCake() {
Cake.call(this);
/* inherit 'setBakingTemperature' privately */
var setBakingTemperature = this.setBakingTemperature;
delete this.setBakingTemperature;
setBakingTemperature(300);
}
ChocolateCake.prototype = Object.create(Cake.prototype, {
constructor: {value: ChocolateCake}
});
var chocolateCake = new ChocolateCake();
chocolateCake.setBakingTemperature(); /* throws TypeError exception */
chocolateCake.getBakingTemperature(); /* 300 */
chocolateCake.bake(); /* Baking the cake at 300 °C */
Update :
Using @p.kamps idea, there is another way to accomplish this. This approach has the advantage that the child class has the option to choose the properties it wants to inherit from the base class, and doesn't need to care about the other properties.
var Cake = function() {
var bakingTemperature = 250;
var setBakingTemperature = function(temperature) {
bakingTemperature = Math.min(temperature, 400);
}
this.inheritSetBakingTemperature = function() {
if (this instanceof Cake) {
return setBakingTemperature;
}
return null;
}
this.getBakingTemperature = function() {
return bakingTemperature;
}
}
Cake.prototype.bake = function() {
console.log("Baking the cake at " + this.getBakingTemperature() + " °C");
}
var ChocolateCake = function() {
Cake.call(this);
/* inherit 'setBakingTemperature' privately */
var setBakingTemperature = this.inheritSetBakingTemperature();
setBakingTemperature(300);
}
ChocolateCake.prototype = Object.create(Cake.prototype, {
constructor: {value: ChocolateCake}
});
var chocolateCake = new ChocolateCake();
chocolateCake.setBakingTemperature(); /* throws TypeError exception */
chocolateCake.getBakingTemperature(); /* 300 */
chocolateCake.bake(); /* Baking the cake at 300 °C */