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

查看:18
本文介绍了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
})();

用于自调用匿名函数.

我想知道一些事情.首先,是什么让顶级示例真正起作用?为什么需要 bang 才能使这个语句在语法上正确?我还被告知 + 有效,我相信其他一些代替 !

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天全站免登陆