这种做法在JavaScript中叫什么?[英] What is this practice called in JavaScript?

本文是小编为大家收集整理的关于这种做法在JavaScript中叫什么?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

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

(function(){

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


})();

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

推荐答案

该模式称为自我发电,a 自我驱动功能.它可以创建一个封闭,但这是模式的效果(也许是预期效果),而不是模式本身.

其他推荐答案

要澄清下面的评论, 最多的时间它创建了封闭,它可以使您的变量范围范围为局部闭合,以不创建全局变量,都可以保持清洁并避免对这些变量的任何潜在不需要的更改.

这里有一些出色的答案可以解释为什么更多: javascript闭合如何工作?

当范围内的某些东西暴露于外部范围时,这只是创建,通常是通常,但是我不能确定您的示例没有看到更多代码.如果什么都没暴露,则不会创建封闭...否则它只是立即执行的匿名函数.

})();格式在末尾,与});相反,实际上是在呼吁闭合即可立即执行,没有参数.如果您有东西,例如})(something);,那么something将作为第一个参数传递:(function(somethingParam){.

其他推荐答案

包装函数称为匿名(它没有名称,并且未分配给变量)自我执行(它本身就是立即执行)函数.

我不记得看到此模式的确切名称,但是它防止了变量泄漏到全局范围.

本文地址:https://www.itbaoku.cn/post/627488.html

问题描述

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?

推荐答案

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.

其他推荐答案

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){.

其他推荐答案

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.