¿Cuál es el propósito de la función autoejecutable en JavaScript?

La función anónima autoejecutable es una función especial que se invoca justo después de definirla. No es necesario llamar a esta función en ninguna parte del script. Este tipo de función no tiene nombre y, por lo tanto, se denomina función anónima. La función tiene un conjunto final de paréntesis. Los parámetros para esta función se pueden pasar entre paréntesis.

Sintaxis:

(function (parameters) {
    // Function body
})(parameters);

Ejemplo:

<!DOCTYPE html>
<html>
  
<head>
    <title>
        What is the purpose of self
        executing function in JavaScript?
    </title>
</head>
  
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
      
    <b>
        What is the purpose of self 
        executing function in JavaScript?
    </b>
      
    <p>
        This page was generated on: 
        <span class="output"></span>
    </p>
      
    <script type="text/javascript">
        (function () {
            date = new Date().toString();
              
            document.querySelector('.output').textContent
                        = date;
        })();
    </script>
</body>
  
</html>

Producción:
self-exec

¿Por qué usar una función anónima?
La ventaja de usar una función anónima en lugar de escribir el código directamente es que las variables y funciones definidas dentro de la función anónima no están disponibles para el código externo. Esto evita que el espacio de nombres global se llene de variables y funciones que pueden no ser necesarias más. También se puede utilizar para habilitar el acceso solo a las variables y funciones. Esto se muestra en los siguientes ejemplos.

Acceder a una variable desde fuera de la función anónima: este ejemplo muestra que acceder al objeto de fecha desde fuera de la función anónima da como resultado un error.

<!DOCTYPE html>
<html>
  
<head>
    <title>
        What is the purpose of self 
        executing function in JavaScript?
    </title>
</head>
  
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
      
    <b>
        What is the purpose of self
        executing function in JavaScript?
    </b>
      
    <p>
        This page was generated on: 
        <span class="output"></span>
    </p>
      
    <script type="text/javascript">
        (function () {
            let date = new Date().toString();
              
            document.querySelector('.output').textContent
                    = date;
        })();
  
        console.log('The date accessed is: ' + date);
    </script>
</body>
  
</html>                    

Producción:
restrict-access

Permitir el acceso a una variable fuera de la función: este ejemplo muestra que la variable de fecha podría estar disponible fuera de la función haciéndola global.

<!DOCTYPE html>
<html>
  
<head>
    <title>
        What is the purpose of self 
        executing function in JavaScript?
    </title>
</head>
  
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
      
    <b>
        What is the purpose of self 
        executing function in JavaScript?
    </b>
      
    <p>
        This page was generated on: 
        <span class="output"></span>
    </p>
      
    <script type="text/javascript">
        (function () {
            let date = new Date().toString();
            document.querySelector('.output').textContent = date;
      
            // Assign to global window making it
            // accessible to outside
            window.date = date;
        })();
      
        console.log('The date accessed is: ' + date);
    </script>
</body>
  
</html>                    

Producción:
allow-access

Publicación traducida automáticamente

Artículo escrito por sayantanm19 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *