admin管理员组文章数量:1391968
I've seen self-calling functions in Javascript written like this:
(function () {
// foo!
})();
But I've also seen them written like this:
(function () {
// bar!
}());
Syntactically, they do exactly the same thing. My personal habit is the first format, actually, but is there any difference between the two that I should be aware of? Like browser kinks or whatever?
One very trivial thing, for example, is if the second format should work reliably, then it would mean that something like this should be possible as well:
function () {
// shut the front door! saved two characters right there!
}();
It hurts readability a good deal though.
I've seen self-calling functions in Javascript written like this:
(function () {
// foo!
})();
But I've also seen them written like this:
(function () {
// bar!
}());
Syntactically, they do exactly the same thing. My personal habit is the first format, actually, but is there any difference between the two that I should be aware of? Like browser kinks or whatever?
One very trivial thing, for example, is if the second format should work reliably, then it would mean that something like this should be possible as well:
function () {
// shut the front door! saved two characters right there!
}();
It hurts readability a good deal though.
Share Improve this question asked Sep 6, 2012 at 16:51 Richard Neil IlaganRichard Neil Ilagan 14.8k6 gold badges52 silver badges67 bronze badges 5- 1 i think this subject has been discussed more then enough, a little search on SO should have gave you the right answer. – Rafael Herscovici Commented Sep 6, 2012 at 16:58
- Possible duplicate: stackoverflow./q/7197480/401137 – Some Guy Commented Sep 6, 2012 at 16:58
- I always use your first construction and it works without fault. I believe the second will also work. The third will not work in all cases because the interpreter needs to know the difference between an expression and a function definition in some contexts. – jfriend00 Commented Sep 6, 2012 at 16:58
- possible duplicate of Location of parenthesis for auto-executing anonymous JavaScript functions? – scrappedcola Commented Sep 6, 2012 at 17:06
- @Dementic ~ sorry about that. I did do a search, but I guess I didn't get hits because of differences in terminology. – Richard Neil Ilagan Commented Sep 6, 2012 at 17:12
6 Answers
Reset to default 4First:
There is, like you assumed, absolutely no difference between the first two version of your self-invoking anonymous function. No browser klinks, quirks, just es down to personal preference (Douglas Crockford calls the latter form "dog balls" by the way).
Second:
function() {
}()
will not work by design, since that statement creates a function statement/declaration. You need a function expression to immediately invoke itself. To create a function expression you can do multiple things. Putting the whole statement into parenthesis is one way, but you could also write
!function() {
}()
or
+function() {
}
All of these operators will make an expression.
The first two are identical, but if I remember correctly, one of them is preferred by jsLint (I think it’s the second).
The third raises a syntax error in most interpreters, but there are other variants:
!function() {
alert('I’m executing myself!');
}();
var noname = function() {
alert(noname); // undefined!
}();
You can replace the !
with a +
or -
( None of them will make Crockford happy )
This is mostly a convention issue.
(function () {}());
<- one less stack frame before execution (maybe)
(function () {})();
<- executed outside the parenthesis, so one tiny little frame before execution, although I don't like this style, IMO it's visually disconnected.
function () {}();
<- this is just bad practice IMO, it's not immediately obvious that this is an IIFE which is mostly due to convention, but this also has the problem that if you forget a semi-colon before the expression it will, under some conditions silently assign variables the value undefined.
Example:
var x = 0,
y = 1,
z = 3,
function () {
alert("Z is now undefined, instead of throwing a syntax error.");
}();
As mentioned by Andre Meinhold, this is not in expression position.
Pragmatically speaking, JSLint will plain about the first and prefer the second format. Beyond that, it's really personal preference and consistency is key here.
The third format will result in a SyntaxError, so you can't use that. That's because your creating a function declaration, not a function expression. It's the function expression that you're calling when you use the immediate function pattern.
Crockford says to use (function () {...}())
.
It's just a stylistic choice, but it's in the munity's interest to agree upon a convention and (at the risk of starting a flame-war) why not use Crockford's?
Also, keep in mind that (function () { }());
adds potential confusion. Since in a long function, someone not paying attention might see two closing parentheses and only one being opened.
本文标签: javascriptHow should I declare my selfcalling functionStack Overflow
版权声明:本文标题:javascript - How should I declare my self-calling function? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744701845a2620608.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论