arguments is a built-in object in JavaScript. It is similar to NodeList and has the length property, but does not have array methods such as push and pop.
Dean Edwards' format function is very inspiring:
function format(string) {
var args = arguments;
var pattern = new RegExp('%([1-' + args.length + '])', ' g');
return String(string).replace(pattern, function(match, index) {
return args[index];
});
}
alert(format('%1 want to know whose %2 you %3', 'I', 'shirt', 'wear'));
Note three points: 1. The usage of String(string) ensures that string can be any value (such as null, false, 123, etc.) You can never go wrong. 2. Review the replace method. The second parameter can be a function, which is very flexible. 3. The clever combination of arguments and regular expressions realizes the format function.
How to convert arguments into a real array:
var args = Array.prototype.slice.call(arguments);
There is nothing to say about this. The slice method can be used to convert array-like objects into arrays.
Create a function with preset parameters:
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)));
};
}
var majorTom = makeFunc(format, "This is Major Tom to ground control. I'm %1 .");
majorTom("stepping through the door");
majorTom("floating in a most peculiar way");
This is quite interesting. makeFunc is a function that can create functions. The created functions all have the same preset parameters. This avoids code duplication and improves reusability.
Create a self-referential function:
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); comms { alert('s'); }
var somethingWrong = repeat(comms, 3, 2000);
somethingWrong("Can you hear me, major tom?");
is actually the usage of arguments.callee, often Used to reference itself in anonymous functions, here used to implement the repeat function. Note that repeat is a function that creates functions, so there is somethingWrong. The idea is a bit convoluted, but after thinking about it, it is very good.
End with the last sentence in the original text: