Javascript Functions are not reloaded for testing

Source: Internet
Author: User

I continue to study the javascript series of tutorials today. Although it is the foundation, I think it is necessary to study it with your heart. Do not be afraid of difficulties, forget it, or learn it. Which of the following experts did not start from scratch? I want to strengthen my confidence in learning and take it seriously. Although the road is difficult, you will always taste the fragrance at the end.

A function is a js Code that is defined once but can be called or executed multiple times. Sometimes a function has a parameter, that is, a local variable with a value specified when the function is called. Functions often use these parameters to calculate a return value, which is also the value of the function call expression.

The Code is as follows:  

Function box (){

Alert ("Age ");

}

Function box (name, age ){

Return name + age;

}

Alert (box ('caibaojian ', 24); // www.111cn.net

Tip: When a function encounters the first return, the function is terminated and executed.

Iii. argument object

In fact, the function body can use an argument object to receive passed parameters.

The Code is as follows:  


Function box (){

Return arguments [0] + '|' + arguments [1]; // obtain the value of each parameter.

}

Alert (box ('caibaojian ', 24 ));

The length attribute of the arguments object to obtain the number of parameters.

Function box (){

Return arguments. length;

}

Alert (box (1, 2, 3, 4, 5); 5

Javascript Functions are not reloaded.

The Code is as follows:  

Function box (num, ){

Return num +;

}

Function box (num ){

Return num;

}

Alert (box (5, 11); 50 overload is based on the parameter, select the same function with different parameters.

Javascript only recognizes the last cognominal function, in order.

However, javascript can simulate function overloading through its own attributes.

A typical example in the book is meaningless. For example, if a calculator function has two numbers as the parameter, an addition operation is executed. If the parameter is set to three numbers, the multiplication operation is performed.

The most common implementation of this function is

The Code is as follows:  


Function calculate (){
If (arguments. length = 2 ){
Return arguments [0] + arguments [1];
}
If (arguments. length = 3 ){
Return arguments [0] * arguments [1] * arguments [2];
}
}

Alert (calculate (1, 3 ))

This function seems to be fine, but as the demand increases, the if branch will become larger and larger, and the corresponding mode will become increasingly ugly. Although if is not good for language. But we can consider using another policy to achieve this.

This is a new function overload mode. The Code is as follows:

The Code is as follows:  


Var map = function (arr, callback, pThis ){
Var len = arr. length;
Var rlt = new Array (len );
For (var I = 0; I <len; I ++ ){
If (I in arr) rlt [I] = callback. call (pThis, arr [I], I, arr );
}
Return rlt;
}
/**
* The overload method of function parameters is overload to perform mode matching on function parameters. The default dispatcher supports * and... And ?, "*" Represents a parameter of any type, "..." represents multiple parameters of any type ,"? "Generally used ",?... "Indicates zero or any number of parameters.
* @ Method overload
* @ Static
* @ Optional {dispatcher} is used to match the function for parameter distribution.
* @ Param {func_maps} lists the functions that are called according to the matching conditions.
* @ Return {function} the loaded function
*/
Var FunctionH = {
Overload: function (dispatcher, func_maps ){
If (! (Dispatcher instanceof Function )){
Func_maps = dispatcher;
Dispatcher = function (args ){
Var ret = [];
Return map (args, function (o) {return typeof o}). join ();
}
}

Return function (){
Var key = dispatcher ([]. slice. apply (arguments ));
For (var I in func_maps ){
Var pattern = new RegExp ("^" + I. replace ("*", "[^,] *"). replace ("... ",". * ") +" $ ");
If (pattern. test (key )){
Return func_maps [I]. apply (this, arguments );
}
}
}
}
};

FunctionH. overload includes two parameters: one is the dispatcher function that processes matching conditions (which can be defaulted), and the other is a set of function ing tables, by default, the dispatcher function generates a string based on the actual called parameter type. For example, if the three called parameters are 10, "a", and [1, 2], "number, string, array. During the implementation of pattern matching, a regular expression is generated based on each "key" in the function ing table. This regular expression is used to match the return value of the dispatcher function, call the corresponding processing function of this key. Otherwise, the next key is matched in sequence. In this way, the requirement of the computer function can be written

The Code is as follows:  


Var Calculate = FunctionH. overload ({
'Number, number': function (){
Return arguments [0] + arguments [1];
},
'Number, number, number': function (){
Return arguments [0] * arguments [1] * arguments [2];
}
});

Alert (Calculate (1, 2, 3 ));

By the way, the browser-compatible code can also be written in a similar form.

The Code is as follows:  


Var MSIE = navigator. userAgent. indexOf ('msie ')! =-1;
Var foo = FunctionH. overload (function (){
Return MSIE? "IE": "NotIE ";
},{
"IE": function (){
Alert ('this is ie ');
},
"NotIE": function (){
Alert ('notie ');
}
});

Foo ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.