JavaScript Object can have Private Methods

I was watching a JavaScript video tutorial by Douglas Crockford where he explained private members in JavaScript. Although there are no ‘private methods’ in a JavaScript object, we can easily create something similar by defining a function variable with a local scope.

As crockford says “If a value is a function, we can consider it a method”. Let us see a simple example that shows how to use a closure and hide a member.

JavaScript private method

Any attempt to call deleteEmployee will result in the following error:

JavaScript private method

Just keep in mind that by doing it this way, it cannot be a part of the prototype. Call it a hack, trick or a hidden feature, nevertheless it is a very useful tip to hide information inside a JavaScript Object!

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: