javascript 函数领先!句法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5827290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript function leading bang ! syntax
提问by brad
I've been seeing this syntax on a few libraries now and I'm wondering what the benefit is. (note i'm well aware of closures and what the code is doing, I'm only concerned about the syntactical differences)
我现在已经在一些库中看到了这种语法,我想知道有什么好处。(注意我很清楚闭包和代码在做什么,我只关心语法差异)
!function(){
// do stuff
}();
As an alternative to the more common
作为更常见的替代品
(function(){
// do stuff
})();
for self invoking anonymous functions.
用于自调用匿名函数。
I'm wondering a few things. First off, what is allowing the top example to actually work? Why is the bang necessary in order to make this statement syntactically correct? I'm told also that +
works, and I'm sure some others, in place of !
我想知道一些事情。首先,是什么让顶级示例真正起作用?为什么需要 bang 才能使这个语句在语法上正确?我也被告知这+
有效,我相信其他一些代替!
Second, what is the benefit? All I can tell is that it saves a single character, but I can't imagine that's such a huge benefit to attract numerous adopters. Is there some other benefit I"m missing?
第二,有什么好处?我只能说它节省了一个角色,但我无法想象这是一个吸引众多采用者的巨大好处。我还缺少其他什么好处吗?
The only other difference I can see would be the return value of the self invoking function, but in both of these examples, we don't really care about the return value of the function since it's used only to create a closure. So can someone tell me why one might use the first syntax?
我能看到的唯一其他区别是自调用函数的返回值,但在这两个示例中,我们并不真正关心函数的返回值,因为它仅用于创建闭包。那么有人可以告诉我为什么人们可能会使用第一种语法吗?
采纳答案by c-smile
Ideally you should be able to do all this simply as:
理想情况下,您应该能够简单地完成所有这些:
function(){
// do stuff
}();
That means declare anonymous function and execute it. But that will not work due to specifics of JS grammar.
这意味着声明匿名函数并执行它。但由于 JS 语法的特殊性,这将不起作用。
So shortest form of achieving this is to use some expression e.g. UnaryExpression (and so CallExpression):
因此,实现这一点的最短形式是使用一些表达式,例如 UnaryExpression(以及 CallExpression):
!function(){
// do stuff
}();
Or for the fun:
或者为了好玩:
-function(){
// do stuff
}();
Or:
或者:
+function(){
// do stuff
}();
Or even:
甚至:
~function(){
// do stuff
return 0;
}( );
回答by brainjam
In Javascript, a line beginning with function
is expected to be a function statementand is supposed to look like
在 Javascript 中,以 开头的行应该function
是一个函数语句,看起来像
function doSomething() {
}
A self-invoking function like
一个自调用函数,如
function(){
// do stuff
}();
doesn't fit that form (and will cause a syntax error at the first opening paren because there is no function name), so the brackets are used to delineate an anonymous function expression.
不适合该形式(并且会在第一个开头括号处导致语法错误,因为没有函数名称),因此括号用于描述匿名函数表达式。
(function(){
// do stuff
})();
But anything that creates an expression (as opposed to a function statement) will do, so hence the !
. It's telling the interpreter that this is not a function statement. Other than that, operator precedence dictates that the function is invoked before the negation.
但是任何创建表达式(而不是函数语句)的东西都可以,因此!
. 它告诉解释器这不是一个函数语句。除此之外,运算符优先级规定函数在否定之前被调用。
I wasn't aware of this convention, but if it becomes common it may contribute to readability. What I mean is that anybody reading the !function
at the top of a large block of code will expect a self-invocation, the way we are conditioned already to expect the same when we see (function
. Except that we will lose those annoying parentheses. I would expect that's the reason, as opposed to any savings in speed or character count.
我不知道这个约定,但如果它变得普遍,它可能有助于可读性。我的意思是,任何阅读!function
大块代码顶部的 的人都会期望自调用,就像我们已经习惯于在看到(function
. 除了我们会失去那些烦人的括号。我希望这就是原因,而不是速度或字符数的任何节省。
回答by Smoe
Besides the things that were already said, the syntax with the ! is useful if you write javascript without semicolons:
除了已经说过的事情之外,使用 ! 如果您编写没有分号的 javascript,则很有用:
var i = 1
!function(){
console.log('ham')
}()
i = 2
(function(){
console.log('cheese')
})()
The first example outputs 'ham' as expected, but the second will throw an error because the i = 2 statement isn't terminated due to the following parenthesis.
第一个示例按预期输出 'ham',但第二个示例将抛出错误,因为 i = 2 语句由于以下括号而未终止。
Also in concatenated javascript files you don't have to worry if the preceding code has missing semicolons. So no need for the common ;(function(){})(); to make sure your own won't break.
同样在连接的 javascript 文件中,您不必担心前面的代码是否缺少分号。所以不需要常见的 ;(function(){})(); 以确保您自己的不会破裂。
I know my answer is kind of late but i think it haven't been mentioned yet:)
我知道我的回答有点晚了,但我认为还没有提到它:)
回答by Shaz
For one thing, jsPerf shows that using !
(UnaryExpression's) are usually faster. Sometimes they come out to be equal, but when they aren't, I haven't seen the non-bangedone triumph too much over the others yet: http://jsperf.com/bang-function
一方面,jsPerf 表明使用!
(UnaryExpression's) 通常更快。有时它们是平等的,但当它们不是时,我还没有看到非撞击的一个战胜其他人太多:http: //jsperf.com/bang-function
This was tested on the latest Ubuntu with the oldest (per say..) Chrome, version 8. So results may differ of course.
这是在最新的 Ubuntu 上使用最旧的(据说..)Chrome 版本 8 进行测试的。所以结果当然可能会有所不同。
Edit: How about something crazy like delete
?
编辑:怎么样疯狂的东西delete
?
delete function() {
alert("Hi!");
}();
or void
?
或者void
?
void function() {
alert("Hi!");
}();
回答by Geku
回答by Arman McHitarian
So, with negate "!" and all other unary operators like +,-,~, delete, void, a lot has been told, just to sum up:
所以,用否定“!” 以及所有其他一元运算符,如 +、-、~、delete、void,已经说了很多,总结一下:
!function(){
alert("Hi!");
}();
Or
或者
void function(){
alert("Hi!");
}();
Or
或者
delete function(){
alert("Hi!");
}();
And a few more cases with binary operatorsfor fun :)
还有一些有趣的二元运算符案例:)
1 > function() {
alert("Hi!");
}();
Or
或者
1 * function() {
alert("Hi!");
}();
Or
或者
1 >>> function() {
alert("Hi!");
}();
Or even
甚至
1 == function() {
alert("Hi!");
}();
Leaving the ternary for someone else guys :)
将三元留给其他人:)