Home >Web Front-end >JS Tutorial >Javascript Basics Function 'Overloading' Detailed Introduction_Basic Knowledge

Javascript Basics Function 'Overloading' Detailed Introduction_Basic Knowledge

WBOY
WBOYOriginal
2016-05-16 17:18:40998browse

Javascript does not have a function signature like other programming languages ​​(what is a function signature? Simply put, it refers to the function’s accepted parameter type and number of parameters. Some people think that the return type should also be included. You can check the specific concepts online. ).

So Javascript cannot implement overloading with the same method name and different number of parameters like other languages. If you don’t believe me, you can try:

Copy code The code is as follows:

function show(){
alert("1 ");
}
function show(num1){
alert(num1);
}

window.onload=function(){
Show();
            show(2);
       }

Under breakpoint debugging, the show method without parameters will not be executed, and will be overwritten by the show(num1) method.

So "overloading" cannot be implemented in Javascript? The answer is yes, it's just another way. Yes, just use arguments.

So what are arguments? It is a special attribute in JS. It can get the value of the parameter through the subscript index like an array (but it is not an array), and get the number of parameters through length:

Copy code The code is as follows:

function showParamsCount(){
alert("parameters Number: " arguments.length);//Output: Number of parameters: 4
alert("Parameter with subscript index 3:" arguments[3]);//Output: Parameter with subscript index 3 :Hello
}

} window.onload=function(){
showParamsCount("Hello",4,5,"Hello");
}

Another thing to know is that named parameters of functions in JS are not necessary, so if you want to know how many parameters are passed when calling, you still have to get the parameters through arguments.

The following is a simple method overloading:

Copy code The code is as follows:

function showMessage(){
if(arguments. length==1){
                      alert(arguments[0]); ; showMessage("Hi!");
showMessage ("Zhang San","Hi your sister");
}



In this way, JS overloading is realized.

While reading the book Advanced Programming in JS, I discovered that the value of arguments is always synchronized with the value of the corresponding named parameter. I had never noticed this problem before



Copy code

The code is as follows:


function showMessage(name,msg){
arguments[1]="I can change the value of msg";
alert(name "Say:" msg);//Output: Zhang San Say: I can change the value of msg
}

Window.onload=function(){
showMessage("Zhang San","Hi your sister");

Okay, that’s all the basic knowledge about js “overloading”
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn