程序笔记   发布时间:2022-07-18  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了!function () {}(); 自执行匿名函数 Self-Executing Anonymous Function大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

https://stackoverflow.com/questions/3755606/what-does-the-exclamation-mark-do-before-the-function@H_616_1@

JavaScript syntax 101. Here is a function declaration:@H_616_1@

function foo() {}

Note that there's no semicolon: this is just a function declaration. you would need an invocation, foo(), to actually run the function.@H_616_1@

Now, when we add the seemingly innocuous exclamation mark: !function foo() {} it turns it into an expression. it is now a function expression.@H_616_1@

The ! alone doesn't invoke the function, of course, but we can now put () at the end: !function foo() {}() which has higher precedence than ! and instantly calls the function.@H_616_1@

So what the author is doing is saving a byte per function expression; a more readable way of wriTing it would be this:@H_616_1@

(function(){})();

Lastly, ! makes the expression return true. This is because by default all immediately invoked function expressions (IIFE) return undefined, which leaves us with !undefined which is true. Not particularly useful.@H_616_1@

 
 
 

https://stackoverflow.com/questions/9267289/what-does-function-in-javascript-mean@H_616_1@

Self-ExecuTing Anonymous Function - MDN Web Docs Glossary: Definitions of Web-related terms | MDN https://developer.mozilla.org/en-US/docs/Glossary/Self-ExecuTing_Anonymous_Function@H_616_1@

https://developer.mozilla.org/en-US/docs/Glossary/IIFE@H_616_1@

IIFE(立即调用函数表达式)

IIFE( 立即调用函数表达式)是一个在定义时就会立即执行的  JavaScript 函数。@H_616_1@

(function () {
    statements
})();

这是一个被称为 自执行匿名函数 的设计模式,主要包含两部分。第一部分是包围在 圆括号运算符 () 里的一个匿名函数,这个匿名函数拥有独立的词法作用域。这不仅避免了外界访问此 IIFE 中的变量,而且又不会污染全局作用域。@H_616_1@

第二部分再一次使用 () 创建了一个立即执行函数表达式,JavaScript 引擎到此将直接执行函数。@H_616_1@

示例

当函数变成立即执行的函数表达式时,表达式中的变量不能从外部访问。@H_616_1@

(function () {
    var name = "Barry";
})();
// 无法从外部访问变量 name
name // 抛出错误:"Uncaught ReferenceError: name is not defined"

将 IIFE 分配给一个变量,不是存储 IIFE 本身,而是存储 IIFE 执行后返回的结果。@H_616_1@

var result = (function () {
    var name = "Barry";
    return name;
})();
// IIFE 执行后返回的结果:
result; // "Barry"

 @H_616_1@

 @H_616_1@

IIFE

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The name IIFE is promoted by Ben Alman in his blog.@H_616_1@

(function () {
  statements
})();

it is a design pattern which is also known as a Self-ExecuTing Anonymous Function and contains two major parts:@H_616_1@

  1. The first is the anonymous function with lexical scope enclosed within the Grouping Operator (). This prevents accessing variables within the IIFE idiom as well as polluTing the global scope.
  2. The second part creates the immediately invoked function expression () through which the JavaScript ENGIne will directly interpret the function.

Use cases

 

Avoid polluTing the global namespace

Because our application could include many functions and global variables from different source files, it's important to limit the number of global variables. If we have some initiation code that we don't need to use again, we could use the IIFE pattern. As we will not reuse the code again, using IIFE in this case is better than using a function declaration or a function expression.@H_616_1@

(function () {
  // some initiation code
  let firstVariable;
  let secondVariable;
})();

// firstVariable and secondVariable will be discarded after the function is executed.

The module pattern

We would also use IIFE to create private and public variables and methods. For a more sophisticated use of the module pattern and other use of IIFE, you could see the book Learning JavaScript Design Patterns by Addy Osmani.@H_616_1@

const @H_765_343@makeWithdraw = balance => (function(copyBalance) {
  let balance = copyBalance; // This variable is private
  let doBadThings = function() {
    console.log("I will do bad things with your money");
  };
  doBadThings();
  return {
    withdraw: function(amount) {
      if (balance >= amount) {
        balance -= amount;
        return balance;
      } else {
        return "Insufficient money";
      }
    },
  }
})(balance);

const firstAccount = @H_330_365@makeWithdraw(100); // "I will do bad things with your money"
console.log(firstAccount.balance); // undefined
console.log(firstAccount.withdraw(20)); // 80
console.log(firstAccount.withdraw(30)); // 50
console.log(firstAccount.doBadThings); // undefined, this method is private
const secondAccount = @H_330_365@makeWithdraw(20); // "I will do bad things with your money"
secondAccount.withdraw(30); // "Insufficient money"
secondAccount.withdraw(20);  // 0

For loop with var before ES6

We could see the following use of IIFE in some old code, before thE introduction of the statements let and const in ES6 and the block scope. With the statement var, we have only function scopes and the global scope. Suppose we want to create 2 buttons with the texts Button 0 and Button 1 and we click them, we would like them to alert 0 and 1. The following code doesn't work:@H_616_1@

for (var i = 0; i < 2; i++) {
  const button = document.createElement("button");
  button.innerText = "Button " + i;
  button.onclick = function () {
    alert(i);
  };
  document.body.appendChild(button);
}
console.log(i); // 2

When clicked, both Button 0 and Button 1 alert 2 because i is global, with the last value 2. To fix this problem before ES6, we could use the IIFE pattern:@H_616_1@

for (var i = 0; i < 2; i++) {
  const button = document.createElement("button");
  button.innerText = "Button " + i;
  button.onclick = (function (copyOfI) {
    return function() {alert(copyOfI);};
  })(i);
  document.body.appendChild(button);
}
console.log(i); // 2

When clicked, Buttons 0 and 1 alert 0 and 1. The variable i is globally defined. Using the statement let, we could simply do:@H_616_1@

for (let i = 0; i < 2; i++) {
  const button = document.createElement("button");
  button.innerText = "Button " + i;
  button.onclick = function () {
    alert(i);
  };
  document.body.appendChild(button);
}
console.log(i); // Uncaught ReferenceError: i is not defined.

When clicked, these buttons alert 0 and 1.@H_616_1@

 @H_616_1@

Self–invoking function in JavaScript? https://www.tutorialspoint.com/self-invoking-function-in-javascript@H_616_1@

 @H_616_1@

The self-invoking function in JavaScript are known as Immediately Invoked Function Expressions (IIFE). Immediately Invoked Function Expressions (IIFE) is a JavaScript function that executes immediately after it has been defined so there is no need to manually invoke IIFE.@H_616_1@

Following is the code for self-invoking function (IIFE) in JavaScript −@H_616_1@

Example

 Live Demo@H_616_1@

<!DOCTYPE html>
<html lang="javascript:void(0);en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample {
      font-size: 18px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript Immediately Invoked Function Expressions (IIFE)</h1>
<div class="sample"></div>
<script>
   let sampleEle = document.querySELEctor(".sample");
   (function () {
      sampleEle.innerHTML = "This code is invoked immediately as soon as it is defined";
   })();
</script>
</body>
</html>

Output

The above code will produce the following output −@H_616_1@

 @H_616_1@

大佬总结

以上是大佬教程为你收集整理的!function () {}(); 自执行匿名函数 Self-Executing Anonymous Function全部内容,希望文章能够帮你解决!function () {}(); 自执行匿名函数 Self-Executing Anonymous Function所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。