English 中文(简体)
Location of parenthesis for auto-executing anonymous JavaScript functions?
原标题:

I was recently comparing the current version of json2.js with the version I had in my project and noticed a difference in how the function expression was created and self executed.

The code used to wrap an anonymous function in parenthesis and then execute it,

(function () {
  // code here
})();

but now it wraps the auto-executed function in parenthesis.

(function () {
  // code here
}());

There is a comment by CMS in the accepted answer of Explain JavaScript’s encapsulated anonymous function syntax that “both: (function(){})(); and (function(){}()); are valid.”

I was wondering what the difference is? Does the former take up memory by leaving around a global, anonymous function? Where should the parenthesis be located?

最佳回答

They re virtually the same.

The first wraps parentheses around a function to make it a valid expression and invokes it. The result of the expression is undefined.

The second executes the function and the parentheses around the automatic invocation make it a valid expression. It also evaluates to undefined.

I don t think there s a "right" way of doing it, since the result of the expression is the same.

> function(){}()
SyntaxError: Unexpected token (
> (function(){})()
undefined
> (function(){return  foo })()
"foo"
> (function(){ return  foo }())
"foo"
问题回答

In that case it doesn t matter. You are invoking an expression that resolves to a function in the first definition, and defining and immediately invoking a function in the second example. They re similar because the function expression in the first example is just the function definition.

There are other more obviously useful cases for invoking expressions that resolve to functions:

(foo || bar)()

There isn t any difference beyond the syntax.

Regarding your concerns about the second method of doing it:

Consider:

(function namedfunc () { ... }())

namedfunc will still not be in the global scope even though you provided the name. The same goes for anonymous functions. The only way to get it in that scope would be to assign it to a variable inside the parens.

((namedfunc = function namedfunc () { ... })())

The outer parens are unnecessary:

(namedfunc = function namedfunc () { ... })()

But you didn t want that global declaration anyways, did you?

So it it boils down to:

(function namedfunc () { ... })()

And you can reduce it even further: the name is unnecessary since it will never be used (unless your function is recursive.. and even then you could use arguments.callee)

(function () { ... })()

That s the way I think about it (may be incorrect, I haven t read the ECMAScript specification yet). Hope it helps.

The difference just exist because Douglas Crockford doesn t like the first style for IIFEs! (seriuosly) As you can see in this video!!.

The only reason for the existence of the extra wrapping () {in both styles} is to help make that section of code Function Expression, because Function Declaration cannot be immediately called. Some scripts / minify-ers just use +, !, - & ~ instead of too parentheses. Like this:

+function() {  
    var foo =  bar ;  
}();

!function() {  
    var foo =  bar ;  
}();

-function() {  
    var foo =  bar ;  
}();

~function() {  
    var foo =  bar ;  
}();

And all these are exactly the same as your alternatives. Choosing among these cases is completely on your own & makes no difference. { The ones with () produce 1 Byte larger File ;-) }





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签