Objek arguments ECMAScript
- Previous Page Function Overview
- Next Page Function Object
Objek arguments
Dalam kode fungsi, pengembang menggunakan objek khusus argumentsTidak perlu menyebutkan nama parameter secara eksplisitdapat mengakses mereka.
Contoh, dalam fungsi sayHi(), parameter pertama adalah message. Anda juga dapat mengakses nilai ini dengan arguments[0], yaitu nilai parameter pertama (parameter pertama berada di posisi 0, parameter kedua berada di posisi 1, dan seterusnya).
Dengan demikian, tidak perlu menamai parameter secara eksplisit untuk menulis ulang fungsi:
function sayHi() { if (arguments[0] == "bye") { return; } alert(arguments[0]); }
Detecting Parameter Count
You can also use the arguments object to detect the number of function parameters, by referencing the property arguments.length.
The following code will output the number of parameters used each time the function is called:
function howManyArgs() { alert(arguments.length); } howManyArgs("string", 45); howManyArgs(); howManyArgs(12);
The above code will display "2", "0", and "1" in turn.
Note:Unlike other programming languages, ECMAScript does not verify whether the number of parameters passed to the function is equal to the number of parameters defined in the function. Any function defined by the developer can accept any number of parameters (according to Netscape's documentation, up to 255), without causing any errors. Any missing parameters will be passed to the function as undefined, and any extra parameters will be ignored.
Simulate Function Overloading
Use the arguments object to determine the number of parameters passed to the function, thereby simulating function overloading:
function doAdd() { if(arguments.length == 1) { alert(arguments[0] + 5); } else if(arguments.length == 2) { alert(arguments[0] + arguments[1]); } } doAdd(10); // Output "15" doAdd(40, 20); // Output "60"
When there is only one parameter, the doAdd() function adds 5 to the parameter. If there are two parameters, it will add the two parameters together and return their sum. Therefore, doAdd(10) outputs "15", and doAdd(40, 20) outputs "60".
Although not as good as overloading, it is enough to avoid this kind of restriction in ECMAScript.
- Previous Page Function Overview
- Next Page Function Object