I am sure that this must be a pretty common question but after scouring the internets for several hours, I have not found an answer. Here is the question:
Suppose that I have an interface called mammal. Every Mammal has to be able to sleep and eat. (In the future I may throw exceptions for the Mammal class to force children to implement the function).
function Mammal() {};
Mammal.prototype.eat = function() {};
Mammal.prototype.sleep = function() {};
Now suppose that I have a Dog class who implements the Mammal class:
function Dog() {};
Dog.prototype = new Mammal();
Dog.prototype.eat = function() {
...
};
Dog.prototype.sleep = function() {
...
};
The dog’s eat function is very complicated and I would like to use a helper function. I have not been able to figure out what the best way to do this is. Here are the points of consideration:
- The helper function should never be called from outside of the dog class so ideally it should be private.
- The eat function does not have access to private functions (prototypes do not have access to private functions)
- I could put the helper function into a privalaged function but:
- This would still be a public function -> ie: everyone has the right to call it
- It would not be part of the prototype so every dog would need to have its own helper function. If there were lots of dogs this seems inefficient.
- I cannot make the eat function a privaliged function because in order for prototype inheritance to work it needs to be part of the prototype.
Question: How can I call a private function from a prototype function? Or more generally: When an object (child object) inherits from another object (parent object) how should children methods use helper functions and is it possible to make these private?
Define your
Dog“class” in a closure. Then you can have shared priveliged functions. Just know you will have to be careful aboutthisbinding properly when you call it.A function on a prototype is still just a function. So follows the same scope and closure access rules as any another function. So if you define your entire
Dogconstructor and prototype and a secluded island of scope that is the self executing function, you are welcome to share as much as you like without exposing or polluting the public scope.This is exactly how CoffeeScript classes compile down to JS.