📜  javascript run self exectutin object - Javascript (1)

📅  最后修改于: 2023-12-03 14:42:26.943000             🧑  作者: Mango

JavaScript Self-Executing Objects

JavaScript self-executing objects, also known as self-invoking functions or immediately invoked function expressions (IIFE), are functions that are executed immediately upon creation. They are enclosed in parentheses and are invoked by adding a pair of parentheses at the end.

(function() {
  // code here
})();

This pattern is commonly used to create modules in JavaScript, where a module is a self-contained piece of code that provides a specific functionality. It allows developers to encapsulate code and avoid polluting the global namespace.

var module = (function() {
  var privateVariable = 10;
  
  function privateFunction() {
    console.log('Private function');
  }
  
  return {
    publicFunction: function() {
      console.log('Public function');
    }
  };
})();

module.publicFunction();

In the example above, the module is defined as a self-executing function that returns an object with a public function. The privateVariable and privateFunction are not accessible outside of the module, making the code easier to manage and maintain.

Self-executing functions can also take parameters, which can be useful in certain situations.

(function($, window, undefined) {
  // code here
})(jQuery, window);

In the example above, the self-executing function takes the jQuery object and window object as parameters, making them available within the function without polluting the global namespace.

Because self-executing functions are only executed once, they can be used to cache values or initialize variables.

var counter = (function() {
  var count = 0;
  
  return function() {
    return ++count;
  };
})();

console.log(counter()); // 1
console.log(counter()); // 2

In the example above, the counter variable is assigned the result of a self-executing function that returns a function that increments and returns the count variable. This allows the count variable to be private and only accessible through the returned function.

JavaScript self-executing objects are a powerful tool for creating modular and encapsulated code in JavaScript. They allow developers to avoid polluting the global namespace and make code more manageable and maintainable.