Is there any differences between javascript modules:

(function(){}())

vs

(function(){})()

First from book "good parts" by Crockford. Second is code generated with Typescript.

有帮助吗?

解决方案 2

No, there is no difference between those two functions and how they're called. In both cases, you're creating an anonymous function and executing it immediately.

The only reason the "outer" parens are required is that when the JavaScript parser is expecting to see a statement, if it sees function it assumes what follows will be a function declaration. But we want to give a function expression, so by giving it an initial (, we put it into a state where it's expecting an expression.

But where the () to call the function go (after the } or outside the wrapping parens) doesn't make any difference.

其他提示

There is no different. Also you can write the third option if your function doesn't return any value

!function(){}()

No there is no difference, they both work the same. I tend to use the latter... it just seems to make more sense. (function(){}) defines the function and then you call it with (). In either case though, use a (leading)semicolon before the first (. Reference

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top