Private Function in Javascript & Coffeescript

I have not worked in Java but I used to do in when I was doing my graduation. One thing I always liked about Java is encapsulation. It provides really good encapsulation in terms of readability. I don’t know if following code will work or not but this is prototype of encapsulation in Java


I miss that feature in JavaScript. You can create private function in JavaScript but it is not as intuitive or obvious to read. Now before moving ahead you should know how Object Oriented Programming is done in JavaScript or at least how prototype is used. This is how I used to do encapsulation


But it does not give you the notion of Encapsulation which you get while coding in Java. So Coffeescript comes to rescue. Take a look at gist below

If you see the layout of code it does look like pure encapsulation supported by Object Oriented Languages like Java or C++. Look at the definition of doPrivateThings it has = in it instead of ‘ : ‘ which makes it private function. However context of that function will be window. So by doing you are also making sure that context to that function will be of instance of person class, so that in this case other members like name will be accessible todoPrivateThings Isn’t this cool? Now hang on a moment, JavaScript code which Coffeescript Compiler generates is even cooler. It is one of the best JavaScript Hacks I have come across

First person is defined as a variable which assures that person will be accessible anywhere in that scope. Now on line 2 it has been assigned a self executing anonymous function (something which you don’t see in traditional languages). Then inside local instance of person is created and further snippet is exactly same as I have shown in snapshot earlier. In this scope person acts as a class (as its prototype is defined) and same person object is assigned to person from outer scope with help of return which makes outer person closureSince person is now a closure you can still access doPrivateThings by maintaining the context.

It is not great in terms of readability but it is intricate and brain teasing. I don’t know how many of you actually understood the concept here as it is really hard to understand in one read.

I found a good thread on stack overflow about to it in which another method is described which can do encapsulation.


Express your thoughts

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s