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!

No comments:

Post a Comment