这种做法在 JavaScript 中被称为什么?

发布于 2024-09-19 17:21:29 字数 174 浏览 5 评论 0原文

当你将 JavaScript 代码包装在这样的函数中时:

(function(){

  var field = ...;
  function doSomthing(){...
  ...


})();

我注意到这解决了我在很多网页上的范围问题。这种做法叫什么?

When you wrap your JavaScript code in a function like this:

(function(){

  var field = ...;
  function doSomthing(){...
  ...


})();

I noticed that this fixes scoping problems for me on a lot of web pages. What is this practice called?

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

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

发布评论

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

评论(7

偏爱你一生 2024-09-26 17:22:08

它的存在时间比“模式”还要长。这是scheme/lisp 中的常见习惯用法,主要用于封装,尤其是在进行元编程时。

It's been around longer than "patterns". It is a common idiom in scheme/lisp primarily used for encapsulation especially when doing meta programming.

绾颜 2024-09-26 17:22:05

这种做法叫什么?

它称为立即调用函数表达式 ,简而言之:IIFE。它在表达式中定义一个函数,然后该函数自行执行(不将该函数分配给任何标识符)。有时也称为立即执行函数表达式 (IEFE)。

在 Ben Alman 撰写有关它们的博客文章之前,它们也被称为“自调用(匿名)函数”,从那时起这个术语就变得不常见了。它在技术上是不精确的,暗示着递归调用,但实际上并没有发生。

有关语法的详细信息,请参阅解释封装的匿名函数语法自动执行匿名 JavaScript 函数的括号位置?

我注意到这解决了我在很多网页上的范围问题。

是的,此模式的目的是通过执行函数来引入额外的作用域。

该模式有时还可以使用返回值进行扩展,称为(显示)模块模式,或者使用允许递归调用的函数名称进行扩展。

What is this practice called?

It's called an immediately-invoked function expression, in short: IIFE. It defines a function in an expression, which is then executed on its own (without assigning the function to any identifier). It sometimes is also called immediately executed function expression (IEFE).

Before Ben Alman wrote his blog post on them, they were also known as self-invoking (anonymous) functions, a term which became uncommon since then. It was technically imprecise, hinting at a recursive invocation which does not actually happen.

For details on the syntax see Explain the encapsulated anonymous function syntax and Location of parenthesis for auto-executing anonymous JavaScript functions?.

I noticed that this fixes scoping problems for me on a lot of web pages.

Yes, the purpose of this pattern is to introduce an extra scope by executing a function.

The pattern also is sometimes extended with a return value, known as the (revealing) module pattern, or with a name for the function to allow recursive invocations.

┊风居住的梦幻卍 2024-09-26 17:22:02

Douglas Crockford 和 YUI 团队将其称为 模块模式

Douglas Crockford and the YUI team call it the module pattern.

榕城若虚 2024-09-26 17:21:59

Ben Alman 对这种“模式”的常用术语提出了一个有趣的论点。

他关于它的博客文章位于此处 (http://benalman.com/ news/2010/11/immediately-invoked-function-expression/)

如果他的文章对你来说太长了,这里是我的总结(我仍然建议阅读它,因为这个总结遗漏了很多内容):

如果你想要一个命名函数自我执行/调用,它应该看起来像这样:

// Hello, my name is "foo". I am a named function.
// When I am invoked I invoke my self when I am invoked.
function foo(){
   foo();
}

如果你想要一个匿名函数要自我执行/调用,它应该如下所示:

// Hello, I have no name...
//   (though I am assigned to the variable "foo" it's not who I am).
// When I am invoked I invoke my self when I am invoked.
// In ECMAScript 5 I no longer work. :-(
var foo = function(){
    arguments.callee();
};

如果您希望立即执行/调用匿名函数,它应该如下所示:

// Hello, I have no name. I am immediately invoked.
// People sometimes call me a "self-invoking anonymous function"...
//    even though I don't invoke myself.
// Ben Alman calls me an "Immediately-Invoked Function Expression"...
//    or "iffy" for short.
(function(){ /...code.../ }());

我自己对此事的想法:

其他答案是正确的;您所询问的通常称为“自调用匿名函数”。
然而,该术语并不能准确反映实际发生的情况。 “立即调用函数表达式”(简称为“iffy”)似乎是一个更合适的术语。


有趣的事实可以给您的朋友留下深刻印象:

您也可以创建这样的 Iffy:

!function(){
   alert("immediately invoked!");
}();

或者

+function(){
   alert("immediately invoked!");
}();

或者如果您< em>真的 cRaZy ( example ):

!1%-+~function(){
   alert("immediately invoked!");
}();

在大多数浏览器中(如果不是全部,我是不确定)并且效果是相同的(facebook 使用 ! 版本)。

Ben Alman presents an interesting argument on the commonly use terminology for this "pattern".

His blog post about it is here (http://benalman.com/news/2010/11/immediately-invoked-function-expression/).

If his post is too long for you here is my summary (I still recommend reading it as this summary leaves out a lot):

If you want a named function to be self executing/invoking it would should look like this:

// Hello, my name is "foo". I am a named function.
// When I am invoked I invoke my self when I am invoked.
function foo(){
   foo();
}

If you want an anonymous function to be self executing/invoking it should look like this:

// Hello, I have no name...
//   (though I am assigned to the variable "foo" it's not who I am).
// When I am invoked I invoke my self when I am invoked.
// In ECMAScript 5 I no longer work. :-(
var foo = function(){
    arguments.callee();
};

If you want an anonymous function to be immediately executed/invoked it should look like this:

// Hello, I have no name. I am immediately invoked.
// People sometimes call me a "self-invoking anonymous function"...
//    even though I don't invoke myself.
// Ben Alman calls me an "Immediately-Invoked Function Expression"...
//    or "iffy" for short.
(function(){ /...code.../ }());

My own thoughts on the matter:

The other answers are correct; what you are asking about is commonly referred to as a "self invoking anonymous function."
However, that terminology doesn't accurately reflect what is really happening; "Immediately-Invoked Function Expression" (aka "iffy", for short) seems like a more appropriate term.


Fun facts to impress your friends:

You can create an Iffy like this, too:

!function(){
   alert("immediately invoked!");
}();

or

+function(){
   alert("immediately invoked!");
}();

or if you are really cRaZy ( example ):

!1%-+~function(){
   alert("immediately invoked!");
}();

in most browsers (if not all, I'm not sure) and the effect will be the same (facebook uses the ! version).

独夜无伴 2024-09-26 17:21:55

包装函数称为匿名(它没有名称,也没有分配给变量)自执行(它立即执行)函数。

我不记得看到过该模式的确切名称,但它可以防止变量泄漏到全局范围内。

The wrapping function is called an anonymous (it has no name and it isn't assigned to a variable) self-executing (it executes immediately, by itself) function.

I don't remember seeing an exact name for this pattern, but it prevents variable from leaking into global scope.

零度° 2024-09-26 17:21:51

为了澄清下面的评论,大多数在创建闭包时,它会将变量的范围限制在该局部闭包内,而不是创建全局变量,它既可以保持事物的整洁,又可以避免对这些变量进行任何潜在的不需要的更改。

这里有一些很好的答案,可以更多地解释为什么JavaScript 闭包如何工作?

当该作用域内的某些内容暴露于外部作用域时,这只是一个创建闭包,这通常是这种情况,但我无法确定您的示例没有查看更多代码。如果没有暴露任何内容,则不会创建闭包...否则它只是立即执行的匿名函数。

末尾的 })(); 格式与 }); 不同,实际上是调用该闭包立即执行,不带任何参数。如果其中包含某些内容,例如 })(something); 那么 something 将作为第一个参数传递到这里:(function(somethingParam){

To clarify a bit for the comments below, most of the time it's creating a closure, it keeps your variables scoped to that local closure, as to not create global variables, it both keeps things clean and avoids any potential unwanted changes to those variables.

There are some excellent answers here that explain the why a bit more: How does a javascript closure work?

It's only a creating closure when something inside that scope is exposed to an outer scope, which is usually the case, but I can't be sure for your example without seeing more code. If nothing is exposed then no closure's created...otherwise it's just an anonymous function executing immediately.

The })(); format at the end, as opposed to }); is actually calling that closure to execute immediately, with no parameters. If you had something in it, for example })(something); then that something would be passed as the first argument here: (function(somethingParam){.

月野兔 2024-09-26 17:21:47

该模式称为自调用,即自调用函数。它可以创建一个封闭,但这是模式的效果(也许是预期的效果),而不是模式本身。

The pattern is called self-invocation, a self-invoking function. It can create a closure, but that is an effect of the pattern (perhaps the intended effect), not the pattern itself.

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