[JavaScript] Pass all the parameters of a method to the next method step in detail

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.

  • argumentsIt is the parameter list array, you can know how many parameters are passed in,
  • arguments.lengthIndicates the number of parameters passed in

Looking at the following code, I know that it is not good to use argumentsit 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, applythe usage of the proxy, the code is as follows

var _log = console.log;
console.log = function() {
    
    
	return _log.apply(this, arguments);
};

applyIf 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, ...argsthe usefulness of the function is reflected, the code is as follows

var _log = console.log;
console.log = function(...args) {
    
    
	return _log(...args);
};

...argsIt 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...
Please add a picture description

Guess you like

Origin blog.csdn.net/zs1028/article/details/132580714
Recommended