Functions in JavaScript

1. Overloading of functions in JS: For functions in JS, parameters are not required. If a function defines several parameters, the caller can pass it, or not pass it, or only one or two.... You can also pass many, so we can't rely on the number of parameters to distinguish two functions of the same name (understand the code below)

<!DOCTYPE html>
<html>
<head>
    <title>Function Example 7</title>
    <script type="text/javascript">
    
    function fa(a, b)
    {
        alert(a + b);
    }
    
    function fa ()
    {
        alert(10);
    }
    fa( 300,600 );

    var fb = function(a, b){alert(a + b)};
    
    fb = function(){alert(10);};
    
    fb(12, 16); //10
    
    var fc = new Function(a, b, "alert(a+b)");
    fc = new Function("alert(10)" );
         // Functions in JS, parameters are not required, a function assumes that several parameters are defined, then the caller can pass it, or not pass it, or only special One, two.... can also pass many, so we can't rely on the number of parameters to distinguish two functions of the same name
        
        // Overloaded simulation of functions in JS: 
        function doAdd() {
             // arguments object: array of arguments. 
            if (arguments.length == 1 )
            {
                alert(arguments[0] + 10);
            }
            else if (arguments.length == 2)
            {
                alert(arguments[0] + arguments[1]);
            }
        }
        
        // Call a function and get two results by passing the number of parameters. 
        doAdd(10);         // 20 
        doAdd(30, 20);     // 50

    </script>
</head>
<body>

</body>
</html>


2. Access to the parameter array (arguments) of the function in js

<!DOCTYPE html>
<html>
<head>
    <title>Function Example 5</title>
    <script type="text/javascript">
        // arguments parameter array 
        function sayHi() {
            alert( "Hello " + arguments[0] + ", " + arguments[1]); // Access to parameter array 
        }

        sayHi("Nicholas", "how are you today?");

         function howManyArgs() {
            alert(arguments.length); // Length of parameter array 
        }
        
        howManyArgs("ing", 45);    //2
        howManyArgs();                //0
        howManyArgs(12);              //1
    </script>
</head>
<body>

</body>
</html>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325029971&siteId=291194637