Javascript立即调用了函数模式

Javascript immediately invoked function patterns

本文关键字:函数 模式 调用 Javascript      更新时间:2023-09-26

你怎么称呼这些模式? 它们之间有什么区别? 你什么时候会使用每个? 还有其他类似的模式吗?

(function() {
    console.log(this);  // window
})();
(function x() {
    console.log(this);  // window
})();
var y = (function() {
    console.log(this);  // window
})();
var z = function() {
    console.log(this);  // window
}();

编辑:我刚刚找到了两种看似多余的方法来做到这一点,方法是在最后两种情况下命名函数......

var a = (function foo() {
    console.log(this);  // window
})();
var b = function bar() {
    console.log(this);
}();

EDIT2:这是下面@GraceShao提供的另一种模式,它使函数可以在函数范围之外访问。

(x = function () {
    console.log(this);  // window
    console.log(x);     // function x() {}
})();
console.log(x);         // function x() {}
// I played with this as well 
// by naming the inside function 
// and got the following:
(foo = function bar() {
    console.log(this);  // window
    console.log(foo);   // function bar() {}
    console.log(bar);   // function bar() {}
})();
console.log(foo);       // function bar() {}
console.log(bar);       // undefined

以下是您的函数,其中包含一些注释,描述了它们何时/为何可能有用:

(function() {
    // Create a new scope to avoid exposing 
    // variables that don't need to be
    // This function is executed once immediately
})();
(function fact(i) {
    // This named immediately invoked function 
    // is a nice way to start off recursion
    return i <= 1 ? 1 : i*fact(i - 1);
})(10);
var y = (function() {
    // Same as the first one, but the return value 
    // of this function is assigned to y
    return "y's value";
})();
var z = function() {
    /* This is the exact same thing as above 
     (except it is assigned to z instead of y, of course).
     The parenthesis in the above example don't do anything
     since this is already an expression
    */
}();

在这种情况下,它们在语义上都是相同的。ECMAScript 规范包含完整的生产规则,所以这是一个粗略的简化。

另请注意,我忽略了命名函数的名称(x),因为没有使用该名称;它可以在正文中引用,但由于它是一个 FunctionExpression(通过语法生产),它永远不会(在正确的 JS 实现中)污染包含范围 - 请参阅注释。

(function() {
    console.log(this);  // window
})();
(function x() {
    console.log(this);  // window
})();
var y = (function() {
    console.log(this);  // window
})();
var z = function() {
    console.log(this);  // window
}();

减少(在这种情况下,主体无关紧要,它们都"返回未定义"):

(function() {})();
(function x() {})();
var y = (function() {})();
var z = function() {}();

归约(在 ECMAScript 语法中FunctionExpression是一个生产规则,但在这里我用它来表示"一个函数的表达式"):

FunctionExpression()
FunctionExpression()
var y = FunctionExpression()
var z = FunctionExpression()

忽略结果的赋值(总是undefined),可以看出所有形式都是相同的。

快乐编码。

自调用匿名函数。函数体将立即被调用。

(function() {
    console.log(this);  // window
})();

自调用函数。 函数体将立即被调用。您仍然可以在函数体内引用函数x。因此,当您想立即执行某些内容,然后您可能想要迭代它时,您可以直接引用它。

(function x() {
    console.log(this);  // window
    console.log(x);     // function x() {}
})();

右侧的自调用匿名函数将立即调用,返回值将分配给y。 通常当你使用这种模式时,它有一个返回值,否则,y将被undefined

var y = (function() {
    console.log(this);  // window
})();

IMO,它与第三个相同。包含函数的第 3 个的括号只是为了让函数看起来像一个完整的东西。但是两者的功能是相同的。

var z = function() {
    console.log(this);  // window
}();

与第二个类似,但您可以使用以下命令在函数范围之外引用 x:

(x = function () {
    console.log(this);  // window
    console.log(x);     // function x() {}
})();
console.log(x);         // function x() {}

(function() { "使用严格"; 您可以使用此类型

为什么?:立即调用的 IIFE 函数表达式从全局范围中删除变量。这有助于防止变量和函数声明在全局范围内的生存时间超过预期,这也有助于避免变量冲突。

为什么?:当您的代码被缩小并捆绑到单个文件中以部署到生产服务器时,您可能会发生变量和许多全局变量的冲突。IIFE 通过为每个文件提供可变范围来保护您免受这两种情况的影响。

是时候使用 ES06 了

,以下是使用 ES06 中的箭头函数的函数。

 (() => {
    // Create a new scope to avoid exposing variables that don't need to be
    // This function is executed once immediately
})();
(fact = (i)=>(
  // This named immediately invoked function is a nice way to start off recursion
  i <= 1 ? 1 : i*fact(i - 1)
))(10)
const y = (() => (
    // Same as the first one, but the return value of this function is assigned to y
     "y's value"
))();
const z = (() => {
    // This is the exact same thing as above (except it's assigned to z instead of y, of course).
    // The parenthesis in the above example don't do anything since this is already an expression
})();
浏览器中的

JavaScript缺少命名空间。每段代码都在全局范围内运行;因此,内部应用程序代码或第三方依赖项可能会污染范围,同时暴露自己的范围功能片段。污染全局命名空间会导致名称冲突。这种名称冲突在大型项目中很常见,并且可能非常有害。

例如,想象一下,一个第三方库实例化一个名为 utils 的全局变量。如果任何其他库或应用程序代码本身意外覆盖或更改了 utils,则依赖于它的代码可能会以某种不可预测的方式崩溃。如果其他库或应用程序代码意外调用了另一个仅供内部使用的库的函数,也可能发生不可预测的副作用。

 (function () {
      // create state variables
      // make some operation
      // then return those
      const export = {
           export1: () => {},
           export2: () => {}
      }
      return exported
})()

它用于创建专用范围,仅导出要公开的部分。

函数表达式两边的括号

为什么我们甚至需要这些?原因纯粹是句法上的。这JavaScript 解析器必须能够轻松区分函数声明和函数表达式。如果我们省略在函数表达式两边加上括号,并立即调用作为单独的语句function(){}(3),JavaScript 解析器将开始处理它,并将结束,因为它是一个单独的以关键字函数开头的语句,它正在处理函数声明。因为每个函数声明都必须具有一个名称(这里我们没有指定一个),将抛出错误。自避免这种情况,我们将函数表达式放在括号内,向 JavaScript 解析器发出信号,表明它正在处理表达,而不是声明。

您可能还会在某些项目中看到这一点:

+function(){}();
-function(){}();
!function(){}();
~function(){}();

这一次,我们可以使用一元运算符:+ , - , ! , and ~ 。我们这样做向 JavaScript 引擎发出信号,表明它正在处理表达式而不是语句。