请写出几种匿名自执行的写法(至少三种)

Here are a few ways to create anonymous self-executing functions (also known as Immediately Invoked Function Expressions or IIFEs) in JavaScript, along with explanations and slight variations:

1. Classic Wrapped in Parentheses:

This is the most common and traditional approach. The function expression is wrapped in parentheses, which forces it to be treated as an expression, and then immediately invoked with another set of parentheses.

(function() {
  // Your code here
  console.log("IIFE 1 executed");
})();

2. Using the Void Operator:

The void operator evaluates an expression and returns undefined. This can be used to execute the function expression without assigning it to a variable.

void function() {
  // Your code here
  console.log("IIFE 2 executed");
}();

3. Using the Unary Plus Operator:

Similar to the void operator, the unary plus operator can also be used to force the function expression to be evaluated.

+function() {
  // Your code here
  console.log("IIFE 3 executed");
}();

4. Using the Unary Minus Operator (Less Common):

The unary minus operator works similarly, but it will also negate the return value of the function (which is usually discarded anyway in an IIFE).

-function() {
  // Your code here
  console.log("IIFE 4 executed");
}();

5. Arrow Function Variation (ES6+):

With ES6 arrow functions, you can create a slightly more concise IIFE. Note the parentheses around the entire arrow function expression.

(() => {
  // Your code here
  console.log("IIFE 5 executed");
})();

Key Considerations and Explanations:

  • Why use IIFEs? IIFEs create a new scope, preventing variables and functions declared inside from polluting the global scope. This is crucial for avoiding naming conflicts and maintaining clean code, especially in larger projects. They were especially important before ES6 modules became widely adopted.

  • Passing arguments: You can pass arguments to IIFEs just like regular functions:

(function(name) {
  console.log("Hello, " + name + "!");
})("World"); // Output: Hello, World!
  • Returning values: Although less common, IIFEs can return values, which can be assigned to a variable:
let result = (function() {
  return "Some value";
})();
console.log(result); // Output: Some value

These examples demonstrate the most common ways to create IIFEs. The core principle is to treat the function as an expression and then immediately execute it. Choose the style that you find most readable and consistent with your project's coding conventions. In modern JavaScript development with modules, the need for IIFEs has decreased, but they can still be useful in certain situations.

posted @   王铁柱6  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示