为什么使用 (function(){})() 或 !function(){}()?

发布于 2024-12-07 04:38:27 字数 335 浏览 0 评论 0原文

我正在阅读 在 JavaScript 中, ! 的优点是什么? function(){}() over (function () {})()? 然后它击中了我,为什么使用:

(function(){})()!function(){}() 而不仅仅是 function(){}()

有什么具体原因吗?

I was reading In JavaScript, what is the advantage of !function(){}() over (function () {})()? then it hit me, why use :

(function(){})() or !function(){}() instead of just function(){}()?

Is there any specific reason?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

转瞬即逝 2024-12-14 04:38:27

这取决于您在何处编写此内容。 function(){}() 本身会生成语法错误,因为它被评估为函数声明并且需要名称。

通过使用括号或 not 运算符,您可以强制将其解释为不需要名称的函数表达式

如果无论如何它都会被视为表达式,您可以省略括号或运算符。

It depends on where you write this. function(){}() by itself will generate a syntax error as it is evaluated as function declaration and those need names.

By using parenthesis or the not operator, you enforce it to be interpreted as function expression, which don't need names.

In case where it would be treated as expression anyway, you can omit the parenthesis or the operator.

泪之魂 2024-12-14 04:38:27

我猜你在问为什么使用:

var fn = (function(){}());

vs:

var fn = function(){}();

对我来说简单的答案是,RHS 上的函数通常很长,直到我深入到底部并看到结束的 () 时我才意识到我一直在阅读函数表达式而不是函数赋值。

Peter Michaux 的一对重要的 Parens 中有完整的解释。

I guess you are asking why use:

var fn = (function(){}());

versus:

var fn = function(){}();

The simple answer for me is that often the function on the RHS is long and it's not until I get to the bottom and see the closing () that I realise I've been reading a function expression and not a function assignment.

A full explanation is in Peter Michaux's An Important Pair of Parens.

瞄了个咪的 2024-12-14 04:38:27

RobG 的答案略有不同。

许多脚本将整个程序包含在一个函数中,以确保正确的作用域。然后使用末尾的双括号立即运行该函数。但是,这与定义可在页面中使用但最初不运行的函数的程序略有不同。

这两种情况之间的唯一区别是最后两个字符(添加双括号)。由于这些程序可能很长,因此最初的括号表示“这将立即运行”。

程序必须运行吗?不。这对于查看代码并尝试理解它的人有帮助吗?是的。

A slight variation on RobG's answer.

Many scripts encompass the entire program in one function to ensure proper scoping. This function is then immediately run using the double parentheses at the end. However, this is slightly different then programs which define a function that can be used in the page but not run initially.

The only difference between these two scenarios is the last two characters (the addition of the double parentheses). Since these could be very long programs, the initial parenthesis is there to indicate that "this will be run immediately."

Is it necessary for the program to run? No. Is it helpful for someone looking at the code and trying to understand it? Yes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文