Home  >  Article  >  Web Front-end  >  How to prevent overwriting using an immediately called function expression in JavaScript?

How to prevent overwriting using an immediately called function expression in JavaScript?

PHPz
PHPzforward
2023-09-03 19:13:02789browse

如何在 JavaScript 中使用立即调用函数表达式来防止覆盖?

JavaScript allows developers to add functionality and behavior to web pages. Developers need to create multiple functions and variables to add functionality to different parts of the web page.

When developing real-time applications, multiple developers work on the same project. Therefore, it is necessary to avoid inadvertently overwriting functions and variables when working with multiple developers. In this tutorial, we will learn how to prevent overwriting using immediately called function expressions.

Rewrite question

For example, two colleagues are working on the same project, and both define the printAge() function inside the code and merge the code. Now the browser will only execute the last defined function since it overwrites all other function definitions with the same name. As a result, users sometimes see unexpected behavior of web pages. Additionally, this can happen with variable names.

Example (coverage issue)

In the following example, we define two variables with the same name. We display variable values ​​on the web page. In the output, the user can observe that the second "a" variable overwrites the value of the first "a" variable.

<html>
<body>
   <h2> Visualizing the overriding in JavaScript </h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      var a = "Hello World!";
      var a = "Hi World!";
      output.innerHTML = "The value of a is " + a;
   </script>
</body>
</html>

Solution to calling functions immediately to prevent overwriting

JavaScript functions have the functional scope of variables defined inside the function. So, whatever variables we define inside the function, we cannot access them outside the function. Therefore, we can define variables whose scope is limited to the function.

We can use the immediate function call to solve function rewriting, that is, execute the function immediately after defining it. Therefore we don't need to define function names and overriding is prevented.

grammar

Users can use the following syntax to call functions immediately to prevent overrides in JavaScript.

(function () {
   // write JavaScript code here. 
})();

In the above syntax, we have added the function expression inside the brackets. Additionally, we added parentheses after the function definition to call the function immediately.

Example (preventing immediate call function override)

In the example below, we define two functions that are called immediately. In each function, we create an "obj" object variable and store the id, user and age properties. Additionally, we store the printAge() function in the object.

The printAge() functions of the two objects print different messages. Afterwards, we store these two objects in the window object to access them globally. Finally, we executed the printAge() methods of both objects and the user can observe that it printed the original message without overwriting each other.

<html>
<body>
   <h3> Preventing the overriding <i> using the Immediately Invoked Function Expression </i> in JavaScript
   </h3>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById("output");
      (function (window) {
         var obj = {};
         obj.id = "123";
         obj.user = "Shubham";
         var age = "Shubham's Age is 23. <br>";
         obj.printAge = function () {
            output.innerHTML += age;
         }
         window.user1 = obj;
      })(window);
      (function (window) {
         var obj = {};
         obj.id = "342";
         obj.user = "Mukund";
         var age = "Mukund's Age is 18. <br>";
         obj.printAge = function () {
            output.innerHTML += age;
         }
         window.user2 = obj;
      })(window);
      user1.printAge();
      user2.printAge();
   </script>
</body>
</html>

Example

In this example, we also define two function expressions that are called immediately. In the first expression, we define the food object. Additionally, we have defined setId() and setName() methods for the food object and stored them in the window object.

In the second function expression, we define the setId() and setName() methods again and store them in the watch() object. Afterwards, we use the watch and food objects as references to access different methods. In the output we can see that it prints the original message without overwriting it.

<html>
<body>
   <h3> Preventing the overriding <i> using the Immediately Invoked Function Expression </i> in JavaScript </h3>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById("output");
      (function (window) {
         // preparing food data
         var food = {};
         var setId = function () {
            return Date.now();
         }
         var setName = function () {
            return "Apple";
         }
         window.food = {
            setId: setId(),
            setName: setName()
         };
      })(window);
      (function (window) {
      
         // preparing watch data
         var watch = {};
         var setId = function () {
            return Date.now();
         }
         var setName = function () {
            return "Titan";
         }
         window.watch = {
            setId: setId(),
            setName: setName()
         };
      })(window);
      
      // printing values of object
      output.innerHTML = "Food Id: " + food.setId + "<br/>" + "Food Name: " + food.setName + "<br/>" + "Watch Id: " + watch.setId + "<br/>" + "Watch Name: " + watch.setName;
   </script>
</body>
</html>

We learned to use immediate function expressions to prevent overrides when working with JavaScript code. The idea is to define variables in function scope and access them globally through a specific global object, which should not have any overriding names.

The main benefit of using immediately called function expressions to prevent overwriting is to avoid global pollution of variable names. Additionally, it allows us to make the code maintainable and improve the reusability of the code.

The above is the detailed content of How to prevent overwriting using an immediately called function expression in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete