javascript – 这个模式的名称/目的是什么?

前端之家收集整理的这篇文章主要介绍了javascript – 这个模式的名称/目的是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > What do empty parentheses () after a function declaration do in javascript? 4个
我没有找到一个要求类似于这个模式的帖子,抱歉,如果我错过了它.

无论如何,我在许多jQuery插件或脚本中重复看到这种模式:

(function () {
  ...........
}());

它的目的是什么?它有名字吗?

谢谢!

解决方法

它也被称为立即调用函数表达式

Ben Alman有a good article covering IIFE usage,为什么“自动执行匿名函数”不是最好的术语:

One of the most advantageous side effects of Immediately-Invoked
Function Expressions is that,because this unnamed,or anonymous,
function expression is invoked immediately,without using an
identifier,a closure can be used without polluting the current scope.

[… T]the term “self-executing” is somewhat misleading,because it’s not the function that’s executing itself,even though the function is being executed. Also,“anonymous” is unnecessarily specific,since an Immediately Invoked Function Expression can be either anonymous or named. And as for my preferring “invoked” over “executed,” it’s a simple matter of alliteration; I think “IIFE” looks and sounds nicer than “IEFE.”

猜你在找的JavaScript相关文章