To make a JavaScript class with a public method I'd do something like:
function Restaurant() {}
Restaurant.prototype.buy_food = function(){
// something here
}
Restaurant.prototype.use_restroom = function(){
// something here
}
That way users of my class can:
var restaurant = new Restaurant();
restaurant.buy_food();
restaurant.use_restroom();
How do I create a private method that can be called by the buy_food
and use_restroom
methods but not externally by users of the class?
In other words, I want my method implementation to be able to do:
Restaurant.prototype.use_restroom = function() {
this.private_stuff();
}
But this shouldn't work:
var r = new Restaurant();
r.private_stuff();
How do I define private_stuff
as a private method so both of these hold true?
I've read Doug Crockford's writeup a few times but it doesn't seem like "private" methods can be called by public methods and "privileged" methods can be called externally.
You have to put a closure around your actual constructor-function, where you can define your private methods. To change data of the instances through these private methods, you have to give them "this" with them, either as an function argument or by calling this function with .apply(this) :
In general I added the private Object _ temporarily to the object. You have to open the privacy exlipcitly in the "Power-constructor" for the method. If you call the method from the prototype, you will be able to overwrite the prototype-method
Make a public method accessible in the "Power-constructor": (ctx is the object context)
Now I have this openPrivacy:
The apotheosis of the Module Pattern: The Revealing Module Pattern
A neat little extension to a very robust pattern.
There are many answers on this question already, but nothing fitted my needs. So i came up with my own solution, I hope it is usefull for someone:
As you can see this system works when using this type of classes in javascript. As far as I figured out none of the methods commented above did.
I have created a new tool to allow you to have true private methods on the prototype https://github.com/TremayneChrist/ProtectJS
Example:
Here's what i enjoyed the most so far regarding private/public methods/members and instantiation in javascript:
here is the article: http://www.sefol.com/?p=1090
and here is the example:
JSFiddle: http://jsfiddle.net/northkildonan/kopj3dt3/1/