I am trying to wrap my head around the idea of classes, data visibility and closures (specifically in Javascript) and I am On the jQuery docs page for types, it mentions that closures are used to hide data:
The pattern allows you to create objects with methods that operate on data that isn’t visible to the outside—the very basis of object-oriented programming.
The example:
function create() {
var counter = 0;
return {
increment: function() {
counter++;
},
print: function() {
console.log(counter);
}
}
}
var c = create();
c.increment();
c.print(); // 1
By declaring the variable counter with the keyword var, it is already locally scoped inside the function/class definition. As far as I know and can tell, it isn’t accessible from the outside to begin with. Am I missing something from a data visibility perspective.
Second, is there an advantage to writing the class like above versus like below:
function create() {
var counter = 0;
this.increment = function() {
counter++;
}
this.print = function() {
console.log(counter);
}
return this;
}
var c = create();
c.increment();
c.print(); // 1
As I understand it, these are more or less semantically the same thing – the first is just more “jQuery style”. I am just wondering if there is an advantage or other nuance I don’t fully appreciate from the first example. If I am correct, both examples create closures in that they are accessing data declared outside their own scope.
First of all, you are correct that both versions use closures.
The first version is cleaner (in my opinion) and more popular in modern javascript. The major potential drawback of the first style is that you cannot effectively assign objects to the constructor’s prototype, which is useful (and more efficient) if you are creating a lot of the same objects.
The second style, I’ve actually never seen in production Javascript. Normally, you would instantiate
createwithnew, instead of returningthisin thecreate()function, like so: