JavaScript is a prototypal object-oriented programming language, not a classical object-oriented programming language. There are no classes in JavaScript but you can model prototypes as classes due to prototype-class isomorphism:
function CLASS(prototype) {
var constructor = prototype.constructor;
constructor.prototype = prototype;
return constructor;
}
The CLASS
function allows you to create prototypes which look like classes. However they are not classes. Unlike classes in other languages prototypes in JavaScript have no access specifiers. Everything must be either public or hidden inside closures:
var BitSet = CLASS({
constructor: function () {
this.words = [];
},
and: function (set) {
var length = this.words.length, setWords = set.words;
for (var i = 0; i < length; i++) this.words[i] &= setWords[i] || 0;
}
});
In fact it is a good thing that JavaScript doesn't have classes or access specifiers because you really don't need them. Think about it. Do you really need access specifiers in languages like Java either? If everything was public would it really make such a big difference? In my humble opinion it wouldn't.
Some people argue that making everything public is bad because it exposes implementation details and unnecessarily clutters the user API. Not true. Just don't document those properties which you wish to keep private. If the user doesn't need to know about a certain property then just don't document it.
If you need to make a variable private for security purposes then JavaScript has closures. Such properties shouldn't need to be accessed by other objects (even of the same class) anyway. Hence there shouldn't be a situation in which you need to keep a variable private and making it accessible to other classes of objects too.
Finally there are lots of advantages of making properties public:
- Since the property is public you don't need to create closures inside the constructor function.
- Methods can be shared on the prototype. Hence all instances of the class share methods.
- You can separate object initialization from the methods of the object.
- The code is more readable and maintainable.
- Object creation is faster.