在JavaScript中,function(){}()over(function(){})()的优点是什么? [英] In JavaScript, what is the advantage of !function(){}() over (function () {})()?

查看:145
本文介绍了在JavaScript中,function(){}()over(function(){})()的优点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

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

我以前用JavaScript自行执行的匿名函数:

I've long used the following for self-executing, anonymous functions in JavaScript:

(function () { /* magic happens */ })()

最近,我开始看更多的以下模式的实例(例如,在引导中):

Lately, I've started seeing more instances of the following pattern (e.g., in Bootstrap):

!function () { /* presumably the same magic happens */ }()

任何人都知道第二种模式有什么优势?或者,这只是一种风格偏好吗?

Anyone know what the advantage is of the second pattern? Or, is it just a stylistic preference?

推荐答案

这两种不同的技术有一个功能差异以及外观上的差异。

These two different techniques have a functional difference as well as a difference in appearance. The potential advantages of one technique over the other will be due to these differences.

Javascript是一个简洁的语言可能非常重要,因为当页面加载时,下载了Javascript。这意味着,Javascript更简洁,下载时间越快。因此,有细分混淆器压缩Javascript文件以优化下载时间。例如, alert(Hi); 中的空格将被优化为 alert(Hi);

Javascript is a language where concision can be very important, because Javascript is downloaded when the page loads. That means that the more concise the Javascript, the faster the download time. For this reason, there are Javascript minifiers and obfuscators that compress the Javascript files to optimize the download time. For example, the spaces in alert ( "Hi" ) ; would be optimized to alert("Hi");.

记住这一点,比较这两种模式

Keeping this in mind, compare these two patterns


  • 正常关闭 :   (function(){})() 16个字符

  • 否定关闭!function(){}() 15个字符

  • Normal closure:   (function(){})() 16 characters
  • Negated closure: !function(){}() 15 characters

这是一个微型优化,所以我没有找到这是一个特别有说服力的论据,除非你正在做一个代码高尔夫比赛。

This is a micro-optimization at best, so I don't find this a particularly compelling argument unless you are doing a code golf contest.

比较 a b

var a = (function(){})()
var b = !function(){}()

由于一个函数不返回任何东西, a undefined 。由于否定未定义 true b 将评估到 true 。这对于想要否定函数的返回值或者具有一切必须返回的非空值或非定义值迷信的人来说是一个好处。你可以看到一个解释,这是如何工作的这个其他堆栈溢出问题

Since the a function does not return anything, a will be undefined. Since the negation of undefined is true, b will evaluate to true. This is an advantage to people who either want to negate the returned value of the function or have an everything-must-return-a-non-null-or-undefined-value fetish. You can see an explanation for how this works on this other Stack Overflow question.

我希望这可以帮助您了解这个函数声明背后的理由,通常被认为是一个反模式

I hope that this helps you understand the rationale behind this function declaration that would typically be considered an anti-pattern.

这篇关于在JavaScript中,function(){}()over(function(){})()的优点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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