I'm trying to implement the Singleton pattern via iffes and closures. i managed to so but was wandering if there is a difference between both ways (counter and counter2) of using the parentheses.
would love to understand the difference of using parentheses () for invoking the function expression is contained inside the outer parentheses vs using parentheses () for invoking the function expression is outside the wrapping parentheses for the function expression.
var counter = (function sequenceIIFE() {
var current = 0;
return {
getCurrentValue: function() {
return current;
},
getNextValue: function() {
current = current + 1;
return current;
}
};
})();
var counter2 = (function sequenceIIFE() {
var current = 0;
return {
getCurrentValue: function() {
return current;
},
getNextValue: function() {
current = current + 1;
return current;
}
};
}());
console.log(counter.getNextValue());
console.log(counter.getNextValue());
console.log(counter2.getNextValue());
console.log(counter2.getNextValue());
There is no functional difference at all, the grouping operator determines the order in which statements are executed (statements in the group execute first). Since there's only one statement in the operator, a function expression, the position of the grouping operator is unimportant.
However, if you're defining the same singleton twice as in your example, I personally would be using a class instead, simply for readability. And even if you're not defining it twice, a class is cleaner.
var counter2 = new(class {
constructor() {
this.current = 0;
}
getCurrentValue() {
return this.current;
}
getNextValue() {
this.current++;
return this.current;
}
})();
console.log(counter2.getNextValue());
console.log(counter2.getNextValue());
console.log(counter2.getNextValue());
If you're concerned about a fraction of a millisecond of performance on a counter structure, you might also consider simply using a literal object:
var counter2 = {
current: 0,
getCurrentValue() {
return this.current;
},
getNextValue() {
this.current++;
return this.current;
}
};
console.log(counter2.getNextValue());
console.log(counter2.getNextValue());
console.log(counter2.getNextValue());