To commemorate 10 years did not write a blog, the first blog post with such an interesting trick to start it-___-
In ES5, when we call a function, what happens if the argument to be passed is generated based on other functions or conditions, that is, how many arguments are passed in, without altering the original function?
(Of course, you can avoid this article as much as possible, such as changing the parameter to object or array, etc.)
Most people may know that using apply can solve the problem perfectly:
Apply, like Call, takes the first argument as the calling object of the function, overwriting the this pointer within the calling function as the first argument, or, if it is not the object's method, passing in a null.
And the difference is in the arguments that follow, apply to put all the arguments you want to pass in the calling function into an array, and call is appended to the same as the original function.
Since it is an array, it can be controlled to generate an array based on other functions or logical judgments to achieve the purpose of passing in the dynamic number parameter.
But I have a problem with headaches, when you create an object with new to pass in dynamic parameters, a few years before the problem encountered:
If you are using ES6 and have rest parameters, none of the above problems are the problem. Note that the array args preceded by a three point is not a syntax error, but a ES6 provided by the rest parameter, you can understand that the ... args is replaced with the args array, removing the characters after the square brackets.
But is there really no way to achieve ES5? After all, ES6 are mostly grammatical sugars, can be compiled into a Babel class of ES5, with questions, we will use Babel compiled to see what to get:
See the last line was stunned, don't be afraid, let's analyze This code. First dismember, three steps to see:
1. There is no doubt that using concat to connect null with our arguments to an array, as the second parameter of apply, get [null, 1, 2, 3];
2. Let's calculate the Apply, the first parameter Foo replaces the function to invoke the native bind method, and the contents of the second parameter array are passed as the parameters of bind, i.e. get Foo.bind (null, 1, 2, 3);
3. The first parameter of the Bind method, similar to apply, call, modifies the this pointer, and the following parameter can be used to embed the default predecessor parameter value (preset leading argument) for the function. That is, when bind is done, within the first set of parentheses we get an Foo class that has injected three parameter values, called Foowithargs;
Eventually, when we new Foowithargs (); , you don't have to pass in any arguments. Equivalent to New Foo (1, 2, 3);