How to achieve private, public, and privileged members in JavaScript
One core thing about JavaScript that tends to confuse people is how to get private, public, and privileged members. First off one might even question the fact of whether or not they’re useful or needed - and to one degree, they’re not. But like any OOP language that allows for declaration of private and public members, there’s not even a need for them there as well. The fact of the matter is that it helps abstract your application logic in a way that lets you as the publisher of “whatever it is that you’re building” a way to expose which functions are usable to the outside, and those that are just internal interface methods (yes, those functions that do nothing as far as management is concerned).
Granted, I’ve written on this topic briefly when talking about JavaScript namespaces but didn’t get into full detail on how to achieve all three styles, and how it all actually works.
So, let’s get a working code block and demonstrate all three states of private, public, and privileged.
Sample Class Structure
// Can't forget my namespace
var DED = window.DED || {};
DED.Class = function() {
var fn = function(e, id, param, o) {
// process arguments here
};
return {
init : function() {
var o = DED.Class.get('el');
fn.apply(o, arguments);
},
get : function(id) {
return document.getElementById(id);
}
};
}();
Sweet, so as we can see, this is a very basic structure that gives us some class-like structure which enables us to group methods into a container. Some core things to notice first off is the self-invoking structure which immediately returns an object for public use. That’s shown in these core areas:
Self-invoking hi-lighted
DED.Class = function() {
var fn = function(e, id, param, o) {
// process arguments here
};
return {
init : function() {
var o = DED.Class.get('el');
fn.apply(o, arguments);
},
get : function(id) {
return document.getElementById(id);
}
};
}();
Although this may look awkward at first pass, it’s what’s known as an immediate self-invoked function - and in our case, we’re returning an object at declaration-time. Unda-stood?
What’s Private
These are simply the declared members at the top of the function which can only be internally accessed from other members that share its scope. There is one private member in our class which hi-lighted below:
Private members
DED.Class = function() {
var fn = function(e, id, param, o) {
// process arguments here
};
return {
init : function() {
var o = DED.Class.get('el');
fn.apply(o, arguments);
},
get : function(id) {
return document.getElementById(id);
}
};
}();
One quick way to tell that this is a private method is that it simply can’t be accessed from the global playground area via DED.Class.fn() since fn is not defined in the global scope.
What is public
The public is the world outside your office that has real people you can interact with. This includes friends, family, even neighbors…. Public members are accessible outside your Class. In our example, we actually have two public methods, but only one that is entirely public. That method is hi-lighted below:
Public members
DED.Class = function() {
var fn = function(e, id, param, o) {
// process arguments here
};
return {
init : function() {
var o = DED.Class.get('el');
fn.apply(o, arguments);
},
get : function(id) {
return document.getElementById(id);
}
};
}();
It only makes sense to use the classic get() as our token public example.
And what’s privileged
As you might have already guessed by process of elimination, it is our DED.Class.init which is not only public in the sense that it is accessible from the outside world, but it’s privileged because it is accessing a private member. Of course we can’t do anything notty with the private member it’s using - but rather all you get is special privileged access to borrow its functionality. You could also of course entirely wipe out init by just doing the following:
wipe out the init
DED.Class.init = null;
However that still doesn’t let you get at that private fn method that other members may also be borrowing.
Why does all this matter?
Well, it’s more for educational purposes. Do as you will with it. In fact this post is very unlike me, especially without a demo that makes things fly across the screen. I apologize if I didn’t meet the buzzword index criterion.
If this is all gibberish to you - don’t feel bad. Even Jonathan Snook rarely feels the need to go all out on separating private and public members - especially if it’s just you, yourself, and your blog.
References
- Crock’s explanation (the obvious)
- OOP in JS
- Private Static Members in JavaScript




June 29th, 2006 at 6:18 am
I wish that Prototype made use of private members because it was clear that some of the methods were really meant for internal use within the object. It’d make things clearer as to what should or shouldn’t be used. As mentioned, this isn’t overly important for small or personal scripts but if you need to share your work, the clearer it is for everybody, the better.
June 29th, 2006 at 12:50 pm
You could also create the Class as a singleton, as in
new function() { … }. That way, you don’t have to invoke the function and return an object. If I may be free to link to my own articles, I wrote one about scopes and closures some months ago.June 30th, 2006 at 12:02 pm
I also use the
new function() { ... }pattern. The syntax is much less freaky that way.I also tend to name my private functions and variables with underscores, so that I can distinguish at a glance between private stuff in my object and ordinary stuff in the
windownamespace.(I would shave my eyebrows if it would make IE understand Mozilla’s setter/getter syntax. It’s sooooo pretty.)
June 30th, 2006 at 4:02 pm
I would pay you to shave your eyebrows :)
July 1st, 2006 at 9:14 am
Handling private/public members is, as your article proves, possible in JavaScript, but not without leaving the pure JSON style coding behind (ie those members can’t be defined in the same json object as the public members) - and distinguish the way you access private members in your methods by not using this before their names.
This has always seemed kind of messy to me. Therefore I’ve included some methods in my classyJSON-library that lets you decide which members that should be private after you created a class and lets you access those members with “this.” just as you would public members.
Have a look at http://www.thomasfrank.se/classy_json.html
July 1st, 2006 at 11:51 am
tip and trick ? :-)
[code]
var AG = AG || {};
AG.Class = new function() {
// private function (not a method !!!)
function trace(what) {
// private variables (bottom) are always available inside this object
alert([what, internalVar]);
// here “this” scope is not refered to AG.Class Object
// that’s why a private self referer is usefull
if(!what) {
// self can do “everything” and is always a private variable
what = self.get(’anotherelement’);
alert([what, internalVar]);
// well, do you need to set a variable only to AG.Class object ?
self.scope.set(”Hello World”);
alert(self.param);
// did you need to set something only to self private variable ?
self.set(”Hello Private World”);
alert(self.param);
// did you need to sincronize changes ?
// self.set(”test”) || self.scope.set(”test”);
}
};
// public methods
this.init = function() {
if(!self && (self = {})) { // creation of self referer
for(var public in this) self[public] = this[public];
// now you have a self referer for every private fake method
// and you should use self referer to assign these too
self.trace = trace;
// but if you need to apply changes using self to this object
// you should assign a complete referer too
self.scope = this;
};
var obj = AG.Class.get(’element’);
// I prefere this.get(’element’) …
self.trace(obj);
};
this.get = function(id) {
return document.getElementById(id);
};
this.set = function(str) {
this.param = str;
};
this.iNeedAllForJson = function() {
// if you convert AG.Class to JSON self, as trace funciton, is not
// converted (privates), but if you need absolutely
// privates methods too you should convert directly self (or a copy)
// and not the AG.Class object
// just return the self private variable without the scope
var tmpself = {};
for(var method in self) {
if(method !== “scope”)
tmpself[method] = self;
};
return tmpself;
// you could set all private vars to tmpself var
// tmpself.internalVar = internalVar
// and then return private variables too
};
// private variable (not params)
var self,
internalVar = 123;
// public param … just for example
this.param = “nothing”;
};
onload = function() {
AG.Class.init();
alert(AG.Class.param);
};
test
[/code]
July 1st, 2006 at 11:54 am
ooops, Giammarchi and not Giamamrchi :D
P.S. you have my email from some days …
http://www.3site.it/blog/#leftside20
July 1st, 2006 at 10:00 pm
When are you releasing finally CONTACT FORM 1.0 ?
July 2nd, 2006 at 11:27 am
ooops … !!!
…
if(method !== “scopeâ€)
tmpself[method] = self[method]; // not only self, sorry
July 3rd, 2006 at 5:32 am
no, Andr3a!! not HERE Please!
;)
July 7th, 2006 at 1:11 pm
[...] No Related Posts How to achieve private, public, and privileged members in JavaScript One core thing about JavaScript that tends to confuse people is how to get private, public, and privileged members. First off one might even question the fact of whether or not they’re useful or needed - and to one degree, they’re not. But like any OOP language that allows for declaration of private and public members, there’s not even a need for them there as well. The fact of the matter is that it helps abstract your application logic in a way that lets you as the publisher of “whatever it is that you’re building†a way to expose which functions are usable to the outside, and those that are just internal interface methods (yes, those functions that do nothing as far as management is concerned). As an OO programmer that’s relatively new to serious programming in JavScript, this is something that’s bugged me for ages. Thanks very much to Dustin for explaining it all to me :-) Dustin’s sample looks like this (look at his full post for the explanation): [...]
July 12th, 2006 at 10:10 pm
When is finally the Ajax Form been released? Were all waiting for it..! Thanks!
July 14th, 2006 at 5:05 pm
Thanks Dustin, This is what I use now thanks to you, I almost gave up on it because of it complexity, but once you start using this method it really shines!
Check this multiple inherit puppy out:
/* function newObject() richard maloney 2006
Args: 2+ objects
Usage:send in n objects and it’ll return one object inheriting
all the prop & methods of the objects passed in */
function newObject() {
var o=arguments,len=o.length-1,nextObj;
while(len–){
function f() {}
f.prototype =o[0], nextO=o[len+1];
for ( var i in nextO) { f.prototype[i]=nextO[i];}
}
return new f();
}
July 14th, 2006 at 5:14 pm
Nice investigation of JavaScript scoping. I tend to shy away from using any truly private/priveleged members because I’ve found it affects the maintainability of the code, especially when dealing with a large developer base. My preferred method of dealing with this is just to provide documentation listing the public methods that I want people to know about. Sure, they’ll find the other ones if they really want to, but most of the time people seem to be happy with the hammer and nail you give them.
And thanks for the welcome on my blog. I look forward to meeting you.
July 17th, 2006 at 11:56 pm
The downside to overusing features like this is that a new Object is initialized every time -random wrapper- is accessed. I haven’t done any benchmarks on this, but I’m not liking the idea. The alternative would of course be to leave all methods public, which usually works out fine for me (and simplifies unit testing greatly!)
July 18th, 2006 at 7:53 am
[...] How to achieve private, public, and privileged members in JavaScript (tags: javascript) [...]
August 4th, 2006 at 5:55 am
[...] You may reach a point in your path to JavaScript-Fu Mastery where you feel the need to discover the hidden and most advanced secrets of JavaScript. JavaScript is not only about variables, functions and ready-to-use libraries; the true essence of JavaScript lies in the knowledge and correct usage of information hiding through private and privileged members, closures, object orientation, prototypal inheritance and DOM manipulation, to name a few. As an apprentice you must study JavaScript continuously, because the path to Mastery is never ending. A university professor went to visit a famous JavaScript-Fu Master. While the Master quietly served tea, the professor talked about JavaScript-Fu and Web 2.0. The Master poured the visitor’s cup to the brim, and then kept pouring. The professor watched the overflowing cup until he could no longer restrain himself. “It’s overfull! No more will go in!” the professor blurted. “You are like this cup,” the master replied, “How can I show you JavaScript-Fu unless you first empty your cup.” [...]
August 11th, 2006 at 1:48 am
does javascript really need as much as this object oriented programming?
As google and others are trying to implement everything through it, we will fell a big change in javascript programming.
January 15th, 2007 at 7:17 am
Ali wrote:
“does javascript really need as much as this object oriented programming?”
The short answer is no. Not everything revolves around objects, although it probably can made to be. Also, it’s a good technique to use to prevent clashes with other variables in the global scope, that might have been used by co-workers.
Check out another one of Dustin’s articles: JSON for the masses. http://www.dustindiaz.com/json-for-the-masses/
A question for everyone:
Would I be right in saying that you don’t need public variables? IMHO you only really need private and privilaged, as privileged are public anyway, and they don’t ‘have to’ interact with any other privileged members if you don’t want them to.
If this makes sense and I am right, you have Dustin to thank. I just read two of his articles, and they were most excellent.
All the best.
February 22nd, 2007 at 1:09 am
[...] Just use regular function declarations all the time? Well, ok, I guess. The obvious use of using variable declaration is that you are indeed assigning ’something’ to a variable, and a key takeaway is that you can immediately self-invoke the anonymous function and return a different value back to it. This technique as I’ve discussed several times on this blog already is known as the modular format which is most commonly used for information hiding. As to why that’s important, you’ll here why when my book gets published. [...]
April 24th, 2007 at 8:32 pm
I like the wrap it all up approach, but, as far as I can tell, it leaves you constructorless. That’s sad. Did I miss something? How would you give DED.Class a constructor:
or some such thing?
April 24th, 2007 at 9:04 pm
Ok, i just went and figured it out. The pattern is
yeah. does this pass your smell test?
April 24th, 2007 at 9:17 pm
argh. actually, since returning a fn, need to use this. instead of :
May 15th, 2007 at 2:58 pm
Sorry, ’twas my mistake,
I didn’t realize there were additional parameters to YAHOO.util.Event.addListener() function which would allow me to pass in the targeted obj and allow it to also override the execution scope. this.publicmember() now works as i had thought it should! excellent article, by the way. please feel free to delete these last two comments.
thanks, -f!
August 24th, 2007 at 1:53 pm
Greetings Dustin,
I would like to note that your auto instantiation technique leaves your class lacking. DED.Class then becomes an instance of your anonymous class. If you attempt to say
things will fail. If you just left out the execution parenthesis, than the proposed syntax would work and you’d be able to create any amount of Objects of that Class.
Cheers,
Matt
September 19th, 2007 at 3:59 am
As google and others are trying to implement everything through it, we will fell a big change in javascript programming.
February 14th, 2008 at 11:02 pm
[...] How to achieve private, public and privileged members in Javascript [...]