为什么在匿名函数调用上使用NOT运算符? (a la Knockout 2.1.0) [英] Why use NOT operator on anonymous function call? (a la Knockout 2.1.0)

查看:139
本文介绍了为什么在匿名函数调用上使用NOT运算符? (a la Knockout 2.1.0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

感叹号在功能之前做了什么?

如果你看一下 KnockoutJS 2.1.0的源代码你会在第7行看到这样的代码结构:

If you look at the source code for KnockoutJS 2.1.0 you will see a code structure like this start on line 7:

!function(factory) { ... }(factoryDefinition);

not运算符导致此表达式计算为 true 而不是 undefined ,但为什么要这么麻烦?

The not operator causes this expression to evaluate to true rather than undefined, but why bother?

推荐答案

这是形成一个立即执行的函数表达式的简洁方法。

This is a concise way to form an immediately executed function expression.

传统上,人们使用这两种形式

Traditionally, people have used these two forms

(function(){ }()); // Recommended by Crockford
(function(){ })(); // What most people use

如果你试图使用

function(){ }(); // Syntax error

这将是语法错误,因为它被解释为函数声明而不是一种表达。这就是你需要将函数包装在括号中的原因。

it will be a syntax error, because it is interpreted as a function declaration rather than an expression. This is why you would need to wrap the function in parentheses.

但是如果在函数声明之前放置一元运算符,则不必添加一个cosing括号。 ,它会删除代码中的一个字符,这是一个(非常)微小的性能优势。有几个一元运算符可以用于同样的目的

But if you put a unary operator before the function declaration, you don't have to add a cosing parentheses, and it chops off one character of the code, which is a (very) tiny performance benefit. There are several unary operators that can be used for this same purpose

!function(){ }();
~function(){ }(); 
-function(){ }(); 
+function(){ }(); 

这篇关于为什么在匿名函数调用上使用NOT运算符? (a la Knockout 2.1.0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆