I was looking at some code generated by the TypeScript compiler and I noticed that it is wrapping the function from the revealing object pattern in extra parenthesis. I assume there is a reason for that, what is the reason?
var Castle = (function () {
function Castle(name) {
this.name = name;
}
Castle.prototype.Build = function () {
var element = document.getElementById("textArea");
console.log("Built " + this.name);
};
return Castle;
})();
var test = new Castle("Winterfell");
test.Build();
Notice the outer function being in (). The code seems to work fine without them.
It's just to make it clear what consists of the function expression.
Obviously, that works as well:
var test = function () { return 'test'; }();
However, there's a slight difference with:
var test = (function () { return 'test'; })();
The main difference with the one without the wrapping parenthesis, other than being less clear, is that the context defines whether our function is interpreted as a function expression or a function declaration.
E.g., if you were to remove var test = from the first sample, it would result in a syntax error because a function declaration cannot be invoked.
If their goal was to spit out readable code then that's probably why they chose to use wrapping parenthesis.
On another note, not everyone agrees on the correct IIFE's form.
E.g. Crockford's suggests that:
var test = (function () { return 'test'; }());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With