this series as effective JavaScript 's reading notes.
Here is a typical example of a method that has a mutable parameter list:
Average (1, 2, 3); 2average (1); 1average (3, 1, 4, 1, 5, 9, 2, 6, 5); 4average (2, 7, 1, 8, 2, 8, 1, 8); 4.625
The following is an example that accepts only an array as a parameter:
Averageofarray ([1, 2, 3]); 2averageOfArray ([1]); 1averageOfArray ([3, 1, 4, 1, 5, 9, 2, 6, 5]); 4averageOfArray ([2, 7, 1, 8, 2, 8, 1, 8]); 4.625
There is no doubt that the method of having a mutable parameter list is more concise and flexible, and it can handle any number of parameters. But how do you call a method that has a mutable argument list when the argument is an array?
the answer is to use the built -in Apply method, this method and Pager method is very similar, except Apply The method is to accept an array as a parameter and then call each object in the array as a separate parameter. At the same time, The first parameter of the Apply method is the same as the first parameter of the call method and is used to specify The point of this. So, with the apply method, you can handle the parameters of the array type:
var scores = Getallscores (); Average.apply (null, scores);
Assumptions scores is an array of three elements, the above call is actually:
Average (Scores[0], scores[1], scores[2]);
Another example is the Apply Apply to Dependency arguments variable in the method, about arguments the meaning and use of variables, see Item .
var buffer = {state: [],append:function () {= (var i = 0, n = arguments.length; i < n; i++) {this.state.push (argument S[i]);}};
Append method can be called with any number of arguments because it relies on the arguments variables:
Buffer.append ("Hello,"); Buffer.append (FirstName, "", LastName, "!"); Buffer.append (newline);
Use Apply method, you can call this:
Buffer.append.apply (buffer, getinputstrings ());
It is important to note that the call to the Apply , I passed in the Buffer Object as This the point, which is because the Append is dependent on the implementation of the This variable, you need to explicitly pass in the dependency to ensure that the modification occurs on the correct object.
Summarize:
- Use Apply method to pass parameters of an array type into a method that accepts a mutable argument list
- Use Apply method to specify the first parameter of the This the point
Effective JavaScript Item 21 uses the Apply method to call a function to pass in a mutable argument list