[英]What does the syntax !function() { … } mean?
I found this syntax in the simple, great, wonderful and powerful library knockoutjs : 我在简单,优秀,精彩和强大的库knockoutjs中找到了这种语法:
!function(factory) { ... }
What is the meaning of the not sign ( !
) before the function
declaration? 在function
声明之前,not符号( !
)的含义是什么?
UPDATE: The source code no longer contains this exact syntax. 更新:源代码不再包含此确切语法。
The !
的!
operator behaves as normal, negating the expression. 运算符表现正常,否定表达式。 In this case it is used to force the function to be a function expression instead of a function statement. 在这种情况下,它用于强制函数为函数表达式而不是函数语句。 Since the !
自从!
operator must be applied to an expression (it makes no sense to apply it to a statement, because statements don't have a value), the function will be interpreted as an expression. 运算符必须应用于表达式(将它应用于语句没有意义,因为语句没有值),该函数将被解释为表达式。
This way it can be executed immediately. 这样就可以立即执行。
function(){
alert("foo");
}(); // error since this function is a statement,
// it doesn't return a function to execute
!function(){
alert("foo");
}(); // This works, because we are executing the result of the expression
// We then negate the result. It is equivalent to:
!(function(){
alert("foo");
}());
// A more popular way to achieve the same result is:
(function(){
alert("foo");
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.