This is not a “how to” question. I want to discuss two possible ways of instantiation in JavaScript to find pros and cons of each one.
First one:
function Counter() {
this.counter = 0;
}
Counter.prototype.count = function() {
this.counter += 1;
return this.counter;
};
var counter = new Counter();
console.log("Counter: " + counter.count());
And the second:
var counter = new (function() {
var counter = 0;
this.count = function() {
counter += 1;
return counter;
}
})();
console.log("Counter: " + counter.count());
IMPORTANT NOTE: counter is supposed to be instantiated only once.
The first one looks more structured but the second does not clutter the namespace with unnecessary Counter function.
What do you think? Should I consider these two pieces of code equivalent? Am I missing something?
BTW, I use the 2nd way at the moment. The reason I ask this question is that JSHint states that it’s a “Weird construction.” and proposes to delete new which apparently breaks the code.
The only difference is that
countercan be modified by an external source, at the first method (given the fact the both “classes” will only be initialized once).At the first method,
counteris “publicly” visible and editable property.At the second method,
counteris a local variable, which cannot be modified by anything outside the function.