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!





About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: