JavaScript singular arguments analysis _javascript techniques

Source: Internet
Author: User
Tags time in milliseconds javascript array
In each function, there is a variable named arguments, which holds the parameters of the current invocation in an array-like form. And it's not actually an array, and using the typeof arguments statement tries to return "object", so it can't use a method such as push and pop, as with arrays. Even so, you can still get its value using the subscript and length property.

Write a flexible function
Although the name does not seem well-known, it is true that arguments is a very useful object. For example, you can have a function handle an indefinite number of arguments. In the Base2 library written by Dean Edwards, there is a function called format that fully features this feature:
Copy Code code as follows:

function Format (string) {
var args = arguments;
var pattern = new RegExp ("% ([1-" + Arguments.length + "])", "G");
return string (String). replace (pattern, function (match, index) {
return Args[index];
});
};

This function implements template substitution, where you can use the%1 to%9 tag where you want to dynamically replace, and then the rest of the arguments will replace the places in turn. For example:

Format ("and the '%1 want to know whose%2", "Papers", "shirt", "wear"); the script above will return

"And the papers want to know whose shirt you wear". The point to note here is that even in the definition of the Format function, we define only a parameter named string. Javascript, regardless of the number of parameters defined by the function itself, allows us to pass any number of arguments to a function and save the values to the arguments object of the called function.

Convert to actual array
Although the arguments object is not really a Javascript array, we can use the slice method of the array to convert it to a group, similar to the following code
Copy Code code as follows:

var args = Array.prototype.slice.call (arguments);

In this way, the array variable args contains the values contained by all arguments objects.

function to create preset parameters
Using the arguments object can be short of the amount of Javascript code we write. Here's a function called Makefunc, which returns an anonymous function based on the name of the function you supplied and any number of other arguments. When this anonymous function is invoked, the previously invoked parameter of the merge is passed to the specified function and returned to its return value.
Copy Code code as follows:

function Makefunc () {
var args = Array.prototype.slice.call (arguments);
var func = Args.shift ();
return function () {
return func.apply (NULL, Args.concat (Array.prototype.slice.call (arguments)));
};
}

The first parameter of Makefunc specifies the name of the function that needs to be invoked (yes, there is no error checking in this simple example), and gets removed from the args later. Makefunc returns an anonymous function that invokes the specified function using the Functions object's (Function object) Apply method.

The first parameter of the Apply method specifies the scope, and the essentially scope is the called function. But that would seem a bit complicated in this case, so we set it to null; the second argument is the array, which specifies the parameters of its calling function. Makefunc converts its own arguments and joins the arguments of the anonymous function, which is then passed to the called function.

There is a situation where there is always an output template that is the same, in order to save each time by using the mentioned Format function and specifying duplicate arguments, we can use the Makefunc tool. It returns an anonymous function and automatically generates the content after the template has been specified:
Copy Code code as follows:

var majortom = makefunc (format, "This are Major Tom to ground control.") I ' m%1. ');

You can repeat the specified majortom function like this:
Copy Code code as follows:

MajorTom ("Stepping Through the door");
MajorTom ("floating in a Most peculiar way");

Each time the MajorTom function is called, it fills in the specified template with the first specified parameter. For example, the above code returns:
Copy Code code as follows:

"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 functions
You might think it's cool, don't be so happy, there's a bigger surprise behind it. It (arguments) also has another very useful attribute: callee. Arguments.callee contains the referenced object of the current calling function. So how do we use this thing to do something? Arguments.callee is a very useful anonymous function that calls itself.

Here's a function called repeat, whose arguments require a function reference and two digits. The first number represents the number of times the operation was run, and the second function defines the elapsed time in milliseconds. The following are the relevant code:
Copy Code code as follows:

function repeat (FN, times, delay) {
return function () {
if (times--> 0) {
Fn.apply (null, arguments);
var args = Array.prototype.slice.call (arguments);
var self = Arguments.callee;
settimeout (function () {self.apply (Null,args)}, delay);
}
};
}

The repeat function uses Arguments.callee to obtain the current reference and, after saving it to the self variable, returns an anonymous function to rerun the function that was originally called. Finally, use of settimeout and a combination of anonymous functions to implement deferred execution.

As a simple description, for example, in the usual script, write the following simple function that provides a string and pops up a warning box:
Copy Code code as follows:

function comms (s) {
alert (s);
}

Well, then I changed my mind. I want to write a "special version" of the function, it will repeat three times each interval two seconds. So using my repeat function, you can do it like this:
Copy Code code as follows:

var somethingwrong = Repeat (comms, 3, 2000);
Somethingwrong ("Can You Hear me, Major Tom?");

As expected, a three warning box was ejected for two seconds each time.

In the end, arguments even though it's not always used, it's even a bit spooky, but it's the amazing features (not just that!). It's worth your while to understand it.
Related Article

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.