As in the title, how to pass all the parameters of one method of JavaScript to the next method, how to realize this step, it may be used when the code moves bricks and the method needs to be rewritten, let me tell you about it here.
Parameter passing
Maybe you will write like this, look at the following code
var _log = console.log;
console.log = function(a,b) {
if(b) return _log(a,b);
return _log(a);
};
However, if you encounter a large number of method parameters, look at the following code
var _log = console.log;
console.log = function(a,b,c,d,e,f,g...) {
//省略更多....
if(b && c) return _log(a,b,c);
if(b) return _log(a,b);
return _log(a);
};
Is it necessary to write a lot of lines? If it is not flexible, it will be very tiring to write like that... I have a deep understanding
arguments
Maybe, if you have been in contact with it arguments
, you should think of using this to see if it can be realized.
arguments
It is the parameter list array, you can know how many parameters are passed in,arguments.length
Indicates the number of parameters passed in
Looking at the following code, I know that it is not good to use arguments
it like this. Although it saves writing if()
judgments, it still needs to be written a lot.
var _log = console.log;
console.log = function() {
switch(arguments.length){
//省略更多....
case 3:
return _log(arguments[0],arguments[1],arguments[2]);
case 2:
return _log(arguments[0],arguments[1]);
default:
return _log(arguments[0]);
}
};
proxy method
I heard about proxy, so I thought, can the method be proxy? The answer is yes,
Look at an example, apply
the usage of the proxy, the code is as follows
var _log = console.log;
console.log = function() {
return _log.apply(this, arguments);
};
apply
If the method is not used properly劫持
, it will lead to data security issues, and it is easy to be detected. It is not recommended to use
Pass parameters directly
Pass the parameter list of one method to the next method, just pass the parameter directly,
Look at an example, ...args
the usefulness of the function is reflected, the code is as follows
var _log = console.log;
console.log = function(...args) {
return _log(...args);
};
...args
It is the spread operator, note that this usage is only supported in ECMAScript ES6 and above
I've seen this, but I don't like it...