1

Here are two javascript snippets. i can't understand thedifferent between the two. it seems both allow newing up instances.

var Test1 = (function () {
            function Test1(_x, _y) {
                this.x = _x;
                this.y = _y; console.log("test1");
            }
            return Test1;
        }());
var Test2 = function () {
            function Test2(_x, _y) {
                this.x = _x;
                this.y = _y; console.log("test2");
            }
            return Test2;
        }();

new Test1(1,2); 
new Test2(2,4);

Edit: it looks the same to me BUT, i was poking around with TypeScript and it generated the classes like Type1. there must be a reason they chose to go with that. after all the shortest code is better?

Thanks

Tiju John
  • 530
  • 4
  • 21

2 Answers2

1

Putting parentheses around a function statement forces it into expression context so it is a function expression instead of a function declaration.

However, putting a function statement on the right hand side of a = does that already, so in this case it makes no difference at all.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
1

There is none. In both cases you have self-invoking function, but in case 1 it is surrounded by parentheses which actually do nothing since there is already an IIFE and there is no more scope to hide.

The difference is just like between these two:

var var1 = 1 + 3;
var var2 = (1 + 3);

Talking about IIFE decoration, I would recommended to use the following syntax:

var Test2 = (function () {
    function Test2(_x, _y) {
        this.x = _x;
        this.y = _y; console.log("test2");
    }
    return Test2;
})();

It does the same thing too, but it seems to be a commonly-used and prevalent syntax.

If TypeScript generates such code, it doesn't mean that it is done on any special purpose.
Probably, it is just how TypeScript compiler interprets a context scope and surrounds it with parantheses by default no matter whether it is necessary in this case or not.

Yeldar Kurmangaliyev
  • 30,498
  • 11
  • 53
  • 87
  • "*it is recommended to use the following syntax … and de-facto standard.*" - How did you gather that? – Bergi May 18 '17 at 09:01
  • @Bergi It is my own experience :) I have rarely seen other usages. Just to support my words with a *proof*, I have found a [popular question about IIFEs at SO](http://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript), and 95% of answers are using this approach. I will edit my answer and won't use this too assertive sentence. Thank you for correction :) – Yeldar Kurmangaliyev May 18 '17 at 09:20
  • It's really [purely opinion-based](http://stackoverflow.com/a/8774506/1048572). – Bergi May 18 '17 at 09:26