Home  >  Article  >  Web Front-end  >  JavaScript method overloading effect_javascript skills

JavaScript method overloading effect_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:48:321027browse

Within the JavaScript method, there is a variable array called arguments, which is read-only. All the parameter variables actually passed in are
placed in it. Through it, we can type check the passed parameters. Thereby achieving the effect of overloading.
There are two ways to determine the type of a variable.
1, use typeof statement:

Copy code The code is as follows:

function check( ){
if(typeof arguments[0] == 'string')
alert('The parameter you passed in is a string');
else if(typeof arguments[0] == 'number ')
alert('The parameter you passed in is a number');
}

2, use an attribute constructor that all JavaScript variables have, this attribute points to the Construct the constructor of this variable:
Copy code The code is as follows:

function check(){
if(arguments[0].constructor == String)
alert('The parameter you passed in is a string');
else if(arguments[0].constructor == Number)
alert('The parameter you passed in is a number');
}

Comparison table:
typeof constructor
------------ ---------------
string String
number Number
object Object
function Function
boolean Boolean
object Array
object User
From this comparison table, we can see that typeof cannot accurately determine the specific type, so we use constructor to determine
.
First we define a method to determine the parameter type and number
Copy the code The code is as follows:

function checkArgs(types,args){
// Check the number of parameters
if(types.length != args.length){
return false;
}
// Check parameter type
for(var i=0; iif(args[i].constructor != types[i]){
return false;
}
}
return true;
}

We define a method to apply the above method
Copy code The code is as follows:

function show(){
// Process the call where the parameter is a string
if(checkArgs([ String],arguments)){
alert(arguments[0]);
}
// Process the call whose parameters are a string and a number
else if(checkArgs([String,Number ],arguments)){
var s = '';
for(var i=0; is =arguments[0];
}
alert(s);
// When the parameters do not meet the requirements, give a prompt
}else{
alert('Unsupported parameters');
}
}

When the JavaScript method we define has strict parameter requirements, we can write code in this way.
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