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
Define your Dog
"class" in a closure. Then you can have shared priveliged functions. Just know you will have to be careful about this
binding properly when you call it.
var Dog = (function() {
function Dog() {};
// Common shared private function, available only to Dog.
var privateHelper = function() { ... };
Dog.prototype = new Mammal();
Dog.prototype.eat = function() {
privateHelper()
// Or this if the helper needs to access the instance.
// privateHelper.call(this);
...
};
return Dog;
})();
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 Dog
constructor 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.