javascript - What does the exclamation mark do before the function? - Stack Overflow
javascript - What does the exclamation mark do before the function? - Stack Overflow
JavaScript syntax 101. Here is a function declaration:function foo() {}Note that there's no semicolon: this is a statement; you need a separate invocation of foo() to actually run the function. On the other hand, !function foo() {} is an expression, but that still doesn't invoke the function, but we can now use !function foo() {}() to do that, as () has higher precedence than !. Presumably the original example function doesn't need a self-reference so that the name then can be dropped. So what the author is doing is saving a byte per function expression; a more readable way of writing it would be this:(function(){})();
+1. This really is the best answer here, and sadly, hardly upvoted. Obviously, ! returns boolean, we all know that, but the great point you make is that it also converts the function declaration statement to a function expression so that the function can be immediately invoked without wrapping it in parentheses. Not obvious, and clearly the intent of the coder. – gilly3 Jul 28 '11 at 16:58
沒有留言:
張貼留言