mozilla
Los resultados de tu búsqueda

    Funciones

    This translation is in progress.

    En términos generales, una función es un "subprograma" que puede ser llamado por código externo (o interno en caso de recursión) a la función. Al igual que el programa en sí mismo, una función se compone de una secuencia de declaraciones, que conforman el llamado cuerpo de la función. Se pueden pasar valores a una función, y la función puede devolver un valor.

    En JavaScript, las funciones son objetos de primera clase, es decir, son objetos y se pueden manipular y transmitir al igual que cualquier otro objeto. Concretamente son objetos Function.

    General

    Toda función en JavaScript es un objeto Function. Ver Function para obtener información sobre las propiedades y métodos de los objetos Function.

    Las funciones no son lo mismo que los procedimientos. Una función siempre devuelve un valor, pero un procedimiento, puede o no puede devolver un valor.

    Para devolver un valor especifico distinto del predeterminado, una función debe tener una sentencia return, que especifique el valor a devolver. Una función sin una instrucción return devolverá el valor predeterminado. En el caso de un constructor llamado con la palabra clave new, el valor predeterminado es el valor de su parametro. Para el resto de funciones, el valor predeterminado es undefined.

    Los parámetros en la llamada a una función son los argumentos de la función. Los argumentos se pasan a las funciones por valor. Si la funcióñ cambia el valor de un argumento, este cambio no se refleja globalmente ni en la llamada de la función. Sin embargo, las referenias a objetos también son valores, y son especiales: si la función cambia las propiedades del objeto referenciado, ese cambio es visible fuera de la función, tal y como se muestra en el siguiente ejemplo:

    /* Declare the function 'myFunc' */
     function myFunc(theObject)
     {
       theObject.brand = "Toyota";
     }
     
     /*
      * Declare variable 'mycar';
      * create and initialize a new Object;
      * assign reference to it to 'mycar'
      */
     var mycar = {
       brand: "Honda",
       model: "Accord",
       year: 1998
     };
    
     /* Shows 'Honda' */
     window.alert(mycar.brand);
    
     /* Pass object reference to the function */
     myFunc(mycar);
    
     /*
      * Shows 'Toyota' as the value of the 'brand' property
      * of the object, as changed to by the function.
      */
     window.alert(mycar.brand);

    La palabra clave this no hace referencia a la función que ejecutandose actualment, por lo que debes referirte a los objetos Function por nombre, incluso dentro del cuerpo de la función. Como alternativa, puedes utilizar la propiedad arguments.callee (que no se recomienda).

    Definiendo funciones

    Hay varias formas de definir funciones:

    Declaración de una función (La instrucción function)

    Hay una sintaxis especial para declarar funciones (ver la instrucción function para mas detalles):

    function nombre([param[,
    param[, ...
    param]]]) {instrucciones
    }
    
    nombre
    El nombre de la función.
    param
    El nombre de un argumento que se pasará a la función. Una función puede tener hasta 255 argumentos.
    instrucciones
    Las instruciones que forman el cuerpo de la función.

    Expresión de una función (El operador function)

    Una expresión function es similar a, y tiene la misma sintaxis, que una declaración de función (ver operador function para más detalles):

    function [nombre]([param] [,
    param] [...,
    param]) {instrucciones
    }
    
    nombre
    El nombre de la función, se puede omitir, en ese caso la función se conoce como función anonima.
    param
    El nombre de los argumentos que se pasarán a la función. Una función puede tener hasta 255 argumentos.
    instrucciones
    Las instrucciones que forman el cuerpo de la función.

    La expresión de función flecha (=>)

    Nota: Las expresiones de función Flecha son una tecnología experimental, parte de la proposición Harmony (EcmaScript 6), y no son ampliamente implementadas por los navegadores.

    Una expresión de función flecha tiene una sintaxis más corta y su léxico se une a este valor (ver arrow functions para mas detalles):

    ([param] [, param]) => { instrucciones }
    
    param => expresión
    
    param
    El nombre de los argumentos. Si no hay argumentos se tiene que indicar con (). Para un único argumento no son necesarios los parentesis. (como foo => 1)
    instrucciones o expresión
    Multiples instrucciones deben ser encerradas entre llaves. Una única expresión no necesita llaves. La expresión es, así mismo, el valor de retorno implicito de esa función.

    El constructor Function

    Como todos los demás objetos, los objetos Function se pueden crear mediante el operador new:

    new Function (arg1, arg2, ... argN, functionBody)
    
    arg1, arg2, ... argN
    Ningún nombre, o mas, para ser utilizados por la función como nombres de argumentos formales. Cada uno deve ser una cadena que se ajuste a las reglas de identificadores validos en JavaScript, o a una lista de este tipo de cadenas separadas por comas; por ejemplo "x", "theValue", o "a,b".
    functionBody
    Una cadena conteniendo las instrucciones JavaScript que comprenden la definición de la función.

    Llamar al contructor Function como una función, sin el operador new, tiene el mismo efecto que llamarlo como un constructor.

    Nota: Utilizar el constructor Function no se recomienda, ya que necesita el cuerpo de la función como una cadena, lo cual puede ocasionar que no se optimize correctamente por el motor JS, y puede también causar otros problemas.

    El objeto arguments

    Puedes referirte a los argumentos de una función dentro de la misma, utilizando el objeto arguments. Ver Function.

    Scope and the function stack

    some section about scope and functions calling other functions

    Repaso

    A function can refer to and call itself. There are three ways for a function to refer to itself:

    1. the function's name
    2. arguments.callee
    3. an in-scope variable that refers to the function

    For example, consider the following function definition:

    var foo = function bar() {
       // statements go here
    };
    

    Within the function body, the following are all equivalent:

    1. bar()
    2. arguments.callee()
    3. foo()

    A function that calls itself is called a recursive function . In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). For example, the following loop:

    var x = 0;
    while (x < 10) { // "x < 10" is the loop condition
       // do stuff
       x++;
    }
    

    can be converted into a recursive function and a call to that function:

    function loop(x) {
       if (x >= 10) // "x >= 10" is the exit condition (equivalent to "!(x < 10)")
          return;
       // do stuff
       loop(x + 1); // the recursive call
    }
    loop(0);
    

    However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of a tree structure (e.g. the DOM) is more easily done using recursion:

    function walkTree(node) {
       if (node == null) // 
          return;
       // do something with node
       for (var i = 0; i < node.childNodes.length; i++) {
          walkTree(node.childNodes[i]);
       }
    }

    Compared to the function loop, each recursive call itself makes many recursive calls here.

    It is possible to convert any recursive algorithm to a non-recursive one, but often the logic is much more complex and doing so requires the use of a stack. In fact, recursion itself uses a stack: the function stack.

    The stack-like behavior can be seen in the following example:

    function foo(i) {
       if (i < 0)
          return;
       document.writeln('begin:' + i);
       foo(i - 1);
       document.writeln('end:' + i);
    }
    foo(3);

    which outputs:

    begin:3
    begin:2
    begin:1
    begin:0
    end:0
    end:1
    end:2
    end:3
    

    Nested functions and closures

    You can nest a function within a function. The nested (inner) function is private to its containing (outer) function. It also forms a closure .

    A closure is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

    Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function.

    To summarize:

    • The inner function can be accessed only from statements in the outer function.
    • The inner function forms a closure: the inner function can use the arguments and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function.

    The following example shows nested functions:

    function addSquares(a,b) {
       function square(x) {
          return x * x;
       }
       return square(a) + square(b);
    }
    a = addSquares(2,3); // returns 13
    b = addSquares(3,4); // returns 25
    c = addSquares(4,5); // returns 41
    

    Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function:

    function outside(x) {
       function inside(y) {
          return x + y;
       }
       return inside;
    }
    result = outside(3)(5); // returns 8
    

    Efficiency considerations

    Notice how x is preserved when inside is returned. A closure preserves the arguments and variables in all scopes it contains. Since each call provides potentially different arguments, a closure must be created for each call to the outer function. In other words, each call to outside creates a closure. For this reason, closures can use up a lot of memory. The memory can be freed only when the returned inside is no longer accessible. In this case, the closure of inside is stored in result. Since result is in the global scope, the closure will remain until the script is unloaded (in a browser, this would happen when the page containing the script is closed).

    Because of this inefficiency, avoid closures whenever possible, i.e. avoid nesting functions whenever possible. For example, consider the following example:

    function assignOnclick(element) {
       element.onclick = function() {
          this.style.backgroundColor = 'blue';
       };
    }
    

    This can be rewritten to avoid the closure. However, the anonymous inner function would need to be named and would no longer be private to assignOnclick:

    function assignOnclick(element) {
       element.onclick = element_onclick;
    }
    
    function element_onclick() {
       this.style.backgroundColor = 'blue';
    }
    

    Multiply-nested functions

    Functions can be multiply-nested, i.e. a function (A) containing a function (B) containing a function (C). Both functions B and C form closures here, so B can access A and C can access B. In addition, since C can access B which can access A, C can also access A. Thus, the closures can contain multiple scopes; they recursively contain the scope of the functions containing it. This is called scope chaining . (Why it is called "chaining" will be explained later.)

    Consider the following example:

    function A(x) {
       function B(y) {
          function C(z) {
             alert(x + y + z);
          }
          C(3);
       }
       B(2);
    }
    A(1); // alerts 6 (1 + 2 + 3)
    

    In this example, C accesses B's y and A's x. This can be done because:

    1. B forms a closure including A, i.e. B can access A's arguments and variables.
    2. C forms a closure including B.
    3. Because B's closure includes A, C's closure includes A, C can access both B and A's arguments and variables. In other words, C chains the scopes of B and A in that order.

    The reverse, however, is not true. A cannot access C, because A cannot access any argument or variable of B, which C is a variable of. Thus, C remains private to only B.

    Conflictos de nombre

    When two arguments or variables in the scopes of a closure have the same name, there is a name conflict . More inner scopes take precedence, so the inner-most scope takes the highest precedence, while the outer-most scope takes the lowest. This is the scope chain. The first on the chain is the inner-most scope, and the last is the outer-most scope. Consider the following:

    function outside() {
       var x = 10;
       function inside(x) {
          return x;
       }
       return inside;
    }
    result = outside()(20); // returns 20 instead of 10
    

    The name conflict happens at the statement return x and is between inside's parameter x and outside's variable x. The scope chain here is {inside, outside, global object}. Therefore inside's x takes precedences over outside's x, and 20 (inside's x) is returned instead of 10 (outside's x).

    constructor versus declaration versus expression

    Las diferencias entre la Function constructora, la de declaración y la de expresión.

    Compare lo siguiente:

    1. a function defined with the Function constructor assigned to the variable multiply
      var multiply = new Function("x", "y", "return x * y;");
      
    2. a function declaration of a function named multiply
      function multiply(x, y) {
         return x * y;
      }
      
    3. a function expression of an anonymous function assigned to the variable multiply
      var multiply = function(x, y) {
         return x * y;
      }
      
    4. a function expression of a function named func_name assigned to the variable multiply
      var multiply = function func_name(x, y) {
         return x * y;
      }
      

    All do approximately the same thing, with a few subtle differences:

    • There is a distinction between the function name and the variable the function is assigned to:
      • The function name cannot be changed, while the variable the function is assigned to can be reassigned.
      • The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example:
        var y = function x() {};
        alert(x); // throws an error
        

        The function name also appears when the function is serialized vía el método de la Function 'toString'.

        On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope where the function is declared in.

      • As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other.
    • A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:
      function x() {}
      alert(x); // outputs x serialized into a string
      

      The following example shows how function names are not related to variables functions are assigned to. If a "function variable" is assigned to another value, it will still have the same function name:

      function foo() {}
      alert(foo); // alerted string contains function name "foo"
      var bar = foo;
      alert(bar); // alerted string still contains function name "foo"
      
    • A function defined by a Function does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs:
      function anonymous() {
      }
      

      Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error:

      var foo = new Function("alert(anonymous);");
      foo();
      
    • Unlike functions defined by function expressions or by the Function constructor, a function defined by a function declaration can be used before the function declaration itself. For example:
      foo(); // alerts FOO!
      function foo() {
         alert('FOO!');
      }
      
    • A function defined by a function expression inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).
    • Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function constructor must be parsed every time it is evaluated. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should be avoided whenever possible.

    A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:

    • becomes part of an expression
    • is no longer a "source element" of a function or the script itself. A "source element" is a non-nested statement in the script or a function body:
      var x = 0;               // source element
      if (x == 0) {            // source element
         x = 10;               // not a source element
         function boo() {}     // not a source element
      }
      function foo() {         // source element
         var y = 20;           // source element
         function bar() {}     // source element
         while (y == 10) {     // source element
            function blah() {} // not a source element
            y++;               // not a source element
         }
      }
      

    Examples:

    • // function declaration
      function foo() {}
      
      // function expression
      (function bar() {})
      
      // function expression
      x = function hello() {}
      
    • if (x) {
         // function expression
         function world() {}
      }
      
    • // function statement
      function a() {
         // function statement
         function b() {}
         if (0) {
            // function expression
            function c() {}
         }
      }
      

    Conditionally defining a function

    Functions can be conditionally defined using function expressions or the Function constructor.

    In the following script, the zero function is never defined and cannot be invoked, because 'if (0)' evaluates to false:

    if (0)
       function zero() {
          document.writeln("This is zero.");
       }
    

    If the script is changed so that the condition becomes 'if (1)', function zero is defined.

    Note: Although this looks like a function declaration, this is actually a function expression since it is nested within another statement. Ver las diferencias entre las funciones de declaración y de expresión.

    Note: Some JavaScript engines, not including SpiderMonkey, incorrectly treat any function expression with a name as a function declaration. This would lead to zero being defined, even with the always-false conditional. A safer way to define functions conditionally is to define the function anonymously and assign it to a variable:

    if (0)
       var zero = function() {
          document.writeln("This is zero.");
       }
    

    Functions as event handlers

    In JavaScript, DOM event handlers are functions (as opposed to objects containing a handleEvent method in other DOM language bindings). The functions are passed an event object as the first and only parameter. Like any other parameter, if the event object does not need to be used, it can be omitted in the list of formal parameters.

    Possible event targets in a HTML document include: window (Window objects, including frames), document (HTMLDocument objects), and elements (Element objects). In the HTML DOM, event targets have event handler properties. These properties are lowercased event names prefixed with "on", e.g. onfocus. An alternate and more robust way of adding event listeners is provided by DOM Level 2 Events.

    Note: Events are part of the DOM, not of JavaScript. (JavaScript merely provides a binding to the DOM.)

    The following example assigns a function to a window's "focus" event handler.

    window.onfocus = function() {
       document.body.style.backgroundColor = 'white';
    }
    

    If a function is assigned to a variable, you can assign the variable to an event handler. The following code assigns a function to the variable setBGColor.

    var setBGColor = new Function("document.body.style.backgroundColor = 'white';");
    

    You can use this variable to assign a function to an event handler in several ways. Here are two such ways:

    1. scripting with DOM HTML event properties
      document.form1.colorButton.onclick = setBGColor;
      
    2. HTML event attribute
      <input name="colorButton" type="button"
         value="Change background color"
         onclick="setBGColor();"/>
      

      An event handler set this way is actually a function, named after the attribute, wrapped around the specified code. This is why the parenthesis in "setBGColor()" are needed here (rather than just "setBGColor"). It is equivalent to:

      document.form1.colorButton.onclick = function onclick(event) {
         setBGColor();
      }
      

      Note how the event object is passed to this anonymous function as parameter event. This allows the specified code to use the Event object:

      <input ...
          onclick="alert(event.target.tagName);"/>
      

    Just like any other property that refers to a function, the event handler can act as a method, and this would refer to the element containing the event handler. In the following example, the function referred to by onfocus is called with this equal to window.

    window.onfocus();
    

    A common JavaScript novice mistake is appending parenthesis and/or parameters to the end of the variable, i.e. calling the event handler when assigning it. Adding those parenthesis will assign the value returned from calling the event handler , which is often undefined (if the function doesn't return anything), rather than the event handler itself:

    document.form1.button1.onclick = setBGColor();
    

    To pass parameters to an event handler, the handler must be wrapped into another function as follows:

    document.form1.button1.onclick = function() {
       setBGColor('some value');
    };
    

    Backward compatibility

    JavaScript 1.1 and earlier

    You cannot nest a function statement in another statement or in itself.

    Local variables within functions

    arguments: An array-like object containing the arguments passed to the currently executing function.

    arguments.callee: Specifies the currently executing function.

    arguments.caller: Specifies the function that invoked the currently executing function.

    arguments.length: Specifies the number of arguments passed to the function.

    Ejemplos

    1) Returning a formatted number

    The following function returns a string containing the formatted representation of a number padded with leading zeros.

    // This function returns a string padded with leading zeros
    function padZeros(num, totalLen) {
       var numStr = num.toString();             // Initialize return value as string
       var numZeros = totalLen - numStr.length; // Calculate no. of zeros
       for (var i = 1; i <= numZeros; i++) {
          numStr = "0" + numStr;
       }
       return numStr;
    }
    

    The following statements call the padZeros function.

    var result;
    result = padZeros(42,4); // returns "0042"
    result = padZeros(42,2); // returns "42"
    result = padZeros(5,4);  // returns "0005" 
    

    2) Determining whether a function exists

    You can determine whether a function exists by using the typeof operator. In the following example, a test is peformed to determine if the window object has a property called noFunc that is a function. If so, it is used; otherwise some other action is taken.

     if ('function' == typeof window.noFunc) {
       // use noFunc()
     } else {
       // do something else
     }
    

    Note that in the if test, a reference to noFunc is used—there are no brackets "()" after the function name so the actual function is not called.

    Ver también

    Function, sentencia function, operador function

    Etiquetas y colaboradores del documento

    Contributors to this page: Sheppy, javiertarrio, teoli, Nathymig
    Última actualización por: teoli,
    Ocultar la barra lateral