javascript函数领先爆炸!句法 [英] javascript function leading bang ! syntax

查看:148
本文介绍了javascript函数领先爆炸!句法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在已经在一些库上看到了这种语法,我想知道它的好处是什么。 (注意我很清楚闭包和代码在做什么,我只关心语法差异)

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
}();

作为更常见的替代方案

(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 !

其次,有什么好处?我所能说的只是它节省了一个角色,但我无法想象吸引众多采用者会带来如此巨大的好处。还有其他一些好处我缺席了吗?

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?

推荐答案

理想情况下,您应该能够完成所有这些:

Ideally you should be able to do all this simply as:

function(){
  // do stuff
}(); 

这意味着声明匿名函数但是由于JS语法的细节,这将无法工作。

That means declare anonymous function and execute it. But that will not work due to specifics of JS grammar.

实现这一目标的最短形式是使用一些表达式,例如UnaryExpression(以及CallExpression):

So shortest form of achieving this is to use some expression e.g. UnaryExpression (and so CallExpression):

!function(){
  // do stuff
}(); 

或乐趣:

-function(){
  // do stuff
}(); 

或者:

+function(){
  // do stuff
}(); 

甚至:

~function(){
  // do stuff
  return 0;
}( );

这篇关于javascript函数领先爆炸!句法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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