Can you inherit private functions in JavaScript?
javascript
Solution
You want one instance to inherit the private state of another instance? Sure you can do this in JavaScript. First we need to define a utility function:
function weakBind(functable, prototype, state) {
return function () {
return functable.apply(this, Object.getPrototypeOf(this) === prototype ?
[state].concat(Array.prototype.slice.call(arguments)) : arguments);
};
}
Now we can create our base class as follows:
var Dog = (function () {
function Dog() {
if (this instanceof Dog) {
// constructor code
} else return Object.create(private);
}
var public = Dog.prototype, private = Object.create(public, {
size: {
value: "big"
}
});
public.saySize = weakBind(function (private) {
return "I am a " + private.size + " dog.";
}, public, private);
return Dog;
}());
Now you can create a dog as follows:
var dog = new Dog;
alert(dog.saySize()); // I am a big dog.
alert(dog.size); // undefined
We can inherit the private state as follows:
var Chihuahua = (function () {
function Chihuahua() {
Dog.call(this);
}
var private = Dog();
Object.defineProperty(private, {
size: {
value: "small"
}
});
var public = Chihuahua.prototype = Object.create(Dog.prototype);
public.saySize = weakBind(public.saySize, public, private);
return Chihuahua;
}());
Now you can create a chihuahua as follows:
var chi = new Chihuahua;
alert(chi.saySize()); // I am a small dog.
alert(chi.size); // undefined
See the demo: http://jsfiddle.net/b3Eyn/
Note: I wrote this answer just to show that it's possible to inherit private state in JavaScript. However I would advise you not to use this pattern. If you design your code well then you won't need to inherit private state in the first place.
Problem
I am using a closure to create an object with private and public methods. It looks like this - ``` var Dog = (function() { function Dog() {} var size = 'big'; var _privateSaySize = function() { return 'I am a ' + size + ' dog.'; } Dog.prototype.publicSaySize = function() { return _privateSaySize(); } return Dog; })(); ``` But now I would like to have an object that has only private functions and that is inherited by another object. But is this possible in JavaScript?