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

查看:19
本文介绍了在 JavaScript 中,!function(){}() 比 (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 minifiers混淆器 压缩 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 个字符

这充其量只是一个微优化,所以我不认为这是一个特别引人注目的论点,除非你正在做一个代码高尔夫 比赛.

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.

比较ab的结果值.

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

由于 a 函数不返回任何内容,a 将是 undefined.由于 undefined 的否定是 trueb 将评估为 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(){}() 比 (function () {})() 有什么优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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