JavaScript implements variable parameter functions, and javascript variable parameters

Source: Internet
Author: User

JavaScript implements variable parameter functions, and javascript variable parameters

When using javascript class library functions, you may often encounter a function that can use different numbers of parameters.

For example:

. Code
  1. Exp (var1) exp (var1, var2)

 

 

However, when writing javascript Functions,

Functions cannot have the same name, so they cannot be written separately for different parameter numbers;

The number of parameters must comply with the function settings. Therefore, some parameters in the function declaration must be included. If the number of parameters cannot be called, a few fewer parameters must be written;

......

This problem has been plagued for a long time. Why ?!

I saw someone else's code early this morning ~

 

In the past, we did not declare the number of parameters in the function declaration, but directly received and used them in the function. How can we receive them?

Arguments is a front-end UI framework that can improve development efficiency by 500%!

Although arguments is not an array, it can be used as an array. The subscript starts from 0, so:

Arguments [0] indicates the first parameter received
Arguments [1] indicates the second parameter received
......
And so on ......

In this way, you can call the same function with different parameters ~

Of course, the premise is that the function has set the processing method for this parameter, otherwise it is useless.

By the way, I searched for the introduction of arguments and posted the following:


Arguments attributes
Returns an arguments object for the currently executed function object.

Function. arguments

The function parameter is the name of the currently executed function, which can be omitted.

Description
The arguments attribute allows the function to process variable numbers of parameters. The length attribute of the arguments object contains the number of parameters passed to the function. For a single parameter contained in an arguments object, the access method is the same as the access method of the parameter contained in the array.

Example
The following example illustrates how to use the arguments attribute: a front-end UI framework that can improve development efficiency by 500%!

. Code
  1. Function ArgTest (){
  2. Var I, s, numargs = arguments. length;
  3. S = numargs;
  4. If (numargs <2)
  5. S + = "argument was passed to ArgTest. It was ";
  6. Else
  7. S + = "arguments were passed to ArgTest. They were ";
  8. For (I = 0; I <numargs; I ++)
  9. {
  10. S + = arguments [I] + "";
  11. }
  12. Return (s );
  13. }

 

 

Clever Use of arguments

In Javascript Functions, there is an array object of classes named arguments. It looks so strange and the name is not passed, but many Javascript libraries use its powerful functions. Therefore, every Javascript programmer must be familiar with its features.

It saves the currently called parameters in the form of arrays. In fact, it is not an Array. If you use the typeof arguments statement to try to return "object" (object), it cannot use push and pop methods like Array. Even so, you can use the subscript and length attribute to get its value.

Compile flexible Functions
Although it seems that the name is not passed, it is true that arguments is a very useful object. For example, you can allow a function to process parameters of an indefinite number. In the base2 library written by Dean Edwards, a format function makes full use of this feature: a front-end UI framework that can improve development efficiency by 500%!

. Code
  1. Function format (string ){
  2. Var args = arguments;
  3. Var pattern = new RegExp ("% ([1-" + arguments. length + "])", "g ");
  4. Return String (string). replace (pattern, function (match, index ){
  5. Return args [index];
  6. });
  7. };

 

 

The second parameter of the replace function can be a function. The first parameter of the function can be the matched text, and the second parameter is the matching value, the return value is the text to be replaced.

This function implements template replacement. You can use % 1 to % 9 in the place where dynamic replacement is to be made, and then replace the remaining parameters in sequence. Example: format ("And the % 1 want to know whose % 2 you % 3", "papers", "shirt", "wear ");
The above script will return "And the papers want to know whose shirt you wear ".
Note that, even in the format function definition, we only define a parameter named string. Javascript, regardless of the number of parameters defined by the function, allows us to pass any number of parameters to a function and save these parameter values to the arguments object of the called function.

 

Convert to actual Array
Although the arguments object is not a real Javascript array, we can use the slice Method of the array to convert it into an array, similar to the following code

. Code
  1. Var args = Array. prototype. slice. call (arguments );

 

 

Call (obj, the list of parameters used by the current function) can improve the development efficiency by 500%. Front-end UI framework!

The first parameter of the call method is an object. The uploaded object will call the slice function. because arguments is not an array, you cannot directly call the slice method. Therefore, you can only use the ''object impersonate ''method. In this way, the array variable args contains the values of all arguments objects.

 

Construct a function with Parameters
The arguments object can be used to briefly compile the Javascript code. The following is a function named makeFunc. It returns an anonymous function based on the name of the function you provide and any other number of parameters. When an anonymous function is called, it merges the previously called parameters and submits them to the specified function for running and returns the returned values.

. Code
  1. Function makeFunc (){
  2. Var args = Array. prototype. slice. call (arguments );
  3. Var func = args. shift ();
  4. Return function (){
  5. Return func. apply (null, args. concat (Array. prototype. slice. call (arguments )));};
  6. }

 

 

 

Arguments has a non-enumerative attribute callee (for in cannot be read, which can be determined by HasOwnProterty (name). arguments. callee is the Function object to be executed. Slice has copied the current function pointer, so the first element of args is the function type.

The first parameter of makeFunc specifies the name of the function to be called (yes, there is no error check in this simple example), and the name will be deleted from args. MakeFunc returns an anonymous Function, which calls the specified Function using the Function Object apply method.

The first parameter of the apply method specifies the scope. Basically, the scope is the called function. However, in this example, it looks a little complicated, so we set it to null. The second parameter is an array, which specifies the parameter of the function to be called. MakeFunc converts its own arguments, connects the arguments of the anonymous function, and passes it to the called function.

In one case, there is always a template with the same output. To save every time we use the format function mentioned above and specify repeated parameters, we can use makeFunc. It will return an anonymous function and automatically generate the content after the specified template: a front-end UI framework that can improve development efficiency by 500%!

. Code
  1. Var majorTom = makeFunc (format, "This is Major Tom to ground control. I'm % 1 .");

 

 


You can specify the majorTom function as follows:

. Code
  1. MajorTom ("stepping through the door ");
  2. MajorTom ("floating in a most peculiar way ");

 

 


When the majorTom function is called every time, it uses the first specified parameter to fill in the specified template. For example, the above Code returns:

"This is Major Tom to ground control. I'm stepping through the door ."
"This is Major Tom to ground control. I'm floating in a most peculiar way ."

 

Self-referenced Function
You may think this is cool. Don't be in a hurry. There will be a bigger surprise in the future. It (arguments) also has another very useful property: callee. Arguments. callee contains the referenced object of the currently called function. So how can we use this stuff to do something? Arguments. callee is a very useful method to call its own anonymous functions.

The following is a function named repeat. Its parameters require a function reference and two numbers. The first number indicates the number of running times, while the second function defines the running interval (in milliseconds ). The following is the relevant code: a front-end UI framework that can improve development efficiency by 500%!

. Code
  1. Function repeat (fn, times, delay ){
  2. Return function (){
  3. If (times --> 0 ){
  4. Fn. apply (null, arguments );
  5. Var args = Array. prototype. slice. call (arguments );
  6. Var self = arguments. callee;
  7. SetTimeout (function () {self. apply (null, args)}, delay );
  8. }
  9. };
  10. }

 

 

The repeat function uses arguments. callee to obtain the current reference. After it is saved to the self variable, an anonymous function is returned to re-run the originally called function. Finally, use setTimeout and an anonymous function to implement delayed execution.

As a simple description, for example, you can write the following simple functions that provide strings and bring up a warning box in a common script:

. Code
  1. Function comms (s ){
  2. Alert (s );
  3. }

 

 


Now, I changed my mind. I want to compile a "special version" function that repeats three times and runs every two seconds. Using my repeat function, you can do this as follows:

. Code
  1. Var somethingWrong = repeat (comms, 3, 2000 );
  2. SomethingWrong ("Can you hear me, major tom? ");

 

 


The result is as expected. Three warning boxes are displayed, with a delay of two seconds at a time. A front-end UI framework that can improve development efficiency by 500%!

Finally, even if arguments is not often used, it may seem a little strange, but its amazing features (not just those !) It is worth learning about.


Javascript function as parameter name

A simple example. Test environment: win7 + ie8 + chrome
<Script type = "text/javascript">
Function Add (x, y ){
Alert (x + y );
}
Function Sub (x, y ){
Alert (x-y );
}
Function CallFunc (Fun, x, y ){
If (Fun & (typeof Fun = "function ")){
If (x & y & (typeof x = "number") & (typeof y = "number ")){
Fun (x, y );
} Else {
Console. log (typeof x );
}

} Else {

}
}

CallFunc (Sub, 5, 3 );
</Script>

Javascript js function call Parameters

OTextArea. onkeydown = handle indicates that this event references a function named handle. If () is added, the meaning changes and the return value of the handle function is obtained for this event, the handle function is executed when the event is not triggered. It is recommended that you have time to learn about JS books.

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.