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?