Reputation: 805
I'm trying to use javascript object inheritance where I override a "private" method in the base "class" (in other words, make it a protected method).
Is it possible? Here's my best attempt (which doesn't work)
function Vehicle(color) {
this.color = color;
}
Vehicle.prototype.drive = function() {
_getMessage.call(this);
}
function _getMessage() {
console.log("override this method!")
}
//----------------------------------------------------------------
var Car = (function() {
Car.prototype = Object.create(Vehicle.prototype);
Car.prototype.constructor = Car;
function Car(color) {
Vehicle.call(this, color)
}
function _getMessage() {
console.log("The " + this.color + " car is moving!")
}
return Car;
}());
//----------------------------------------------------------------
$(function() {
var c = new Car('blue');
c.drive()
})
https://plnkr.co/edit/ZMB9izK1W9VuFQHPNsvu?p=preview
Upvotes: 2
Views: 8171
Reputation: 147363
You could introduce a privileged method that can change the private one:
// IIFE to create constructor
var Car = (function(){
// Private method
function _getMessage(text){
console.log('original: ' + text);
}
// Normal constructor stuff
function Car(make){
this.make = make;
}
Car.prototype.getMake = function(){
return this.make;
}
Car.prototype.getMessage = function(){
_getMessage(this.make);
}
// Privileged function to access & change private method
Car.changeGetMessage = function(fn) {
_getMessage = fn;
}
return Car;
}());
// Demonstration
// Create instance
var ford = new Car('Ford');
console.log(ford.getMake());
// Call original method
ford.getMessage();
// Replace original
Car.changeGetMessage(function(text){
console.log('new message: ' + text);
});
// Existing instances get new method
ford.getMessage();
// Create new instance
var volvo = new Car('Volvo');
console.log(volvo.getMake());
// New instances get method too
volvo.getMessage();
Upvotes: 2