apply() method definition
The apply() method of the function and the call method have the same function, but the difference is that the received parameters are different.
The apply() method receives two parameters, one is an object and the other is an array of parameters.
apply() function
1. Used to extend the scope of the function
Example:
var color='red';var o={color:'blue'};function saysColor(){console.log(this.color);}sayColor();//"red"sayColor.apply(o);//"blue"Here, the function is dynamically bound to the object o through the apply() method. At this time, this points to the O object and gets the result "blue".
2. Objects do not need to have any coupling relationship with methods.
Let’s give an example of coupling below to see how to solve this coupling by applying.
var color='red';var o={color:'blue'};function saysColor(){console.log(this.color);}o.sayColor=sayColor;o.sayColor();//"blue"Here, the function is first placed in object o, and the object and method are closely coupled together, and the method call must pass through object o.
It is not as flexible as using apply() and call() methods.
Refactor the above code to get the code in the previous example.
var color='red';var o={color:'blue'};function saysColor(){console.log(this.color);}sayColor();//"red"sayColor.apply(o);//"blue"There is no method bound to the object here, but when it is necessary to use it, use the function's apply or call method to dynamically bind it.
There is no coupling between objects and methods. Here it can also be done through the bind() method provided by ES5.
3. Implement variable parameter function parameter transfer
The following function to calculate the average value of any number
average(,,);average();average(,,,,,,);average(,,,,,,);average(,,,,,,,););
The average function is an example called a mutable parameter or mutable element function (the number of elements of a function refers to its desired number of parameters).
Of course, this function can also be written in the form of a receiving array.
averageOfArray([,,]);averageOfArray([]);averageOfArray([,,,,,,,,]);averageOfArray([,,,,,,,,,]);
Functions that use variable parameters are more concise and elegant. Variable parameter functions have convenient syntax, at least allowing the caller to know in advance how many parameters are provided.
If I have an array like this
var scores=getAllScores();
How to calculate the average value using the average function?
1. Variable parameter function version.
At this time, it can be used in conjunction with the apply() method. Because the function does not use reference this variable, we pass a null for the first parameter. The code is as follows:
var scores=getAllScores();average.apply(null,scores);
2. Direct parameters are in the form of array
Here you can directly pass the array parameters.
var scores=getAllScores();averageOfArray(scores);
I personally think both of the above two forms are OK, but the second one is simpler. Know more about a method, which can be easily dealt with when encountering functions written by others without refactoring the code. This benefit is even more.
4. Implement the value transfer of variable parameter methods
Example: The buffer object contains a mutable parameter append method, which is added to the state array inside the function.
var buffer={state:[],append:function(){for(var i=,n=arguments.length;i<n;i++){this.state.push(arguments[i]);}}};At this time, the append method can accept any multiple parameters.
buffer.append('Hello,');buffer.append('firtName',' ','lastName','!');buffer.append('newLine');Form such as
buffer.append(arg1,arg2,arg3,...)
With this parameter of the apply method, we can specify a computable array to call the append method.
buffer.append.apply(buffer,getInputStrings());
Note: The buffer here is important. If a different object is passed, the append method will try to modify the state property of the wrong object.
hint
• Use the apply method to specify a computable parameter array to call a function with mutable parameters
• Use the first parameter of the apply method to provide a receiver for the variable parameter method
Appendix 1
average function
function average(){var args=[].slice.call(arguments);var sum=args.reduce(function(prev,cur){return prev+cur;});return parseInt(sum/args.length,);}averageOfArray function
function averageOfArray(arr){ var sum=arr.reduce(function(prev,cur){return prev+cur;});return parseInt(sum/arr.length,);}ES5 bind() method
This method creates an instance of a function whose value is bound to the value passed to the bind() function.
For example
var color='red';var o={color:'blue'};function saysColor(){console.log(this.color);}var oSayColor=sayColor.bind(o);oSayColor();//"blue"Compatible with lower versions, refer to the following version:
if (!Function.prototype.bind) {Function.prototype.bind = function(oThis) {if (typeof this !== 'function') {// closest thing possible to the ECMAScript // internal IsCallable functionthrow new TypeError('Function.prototype.bind - what is trying to be bound is not callable');}var aArgs = [].slice.call(arguments, ),fToBind = this,fNOP = function() {},fBound = function() {return fToBind.apply(this instanceof fNOP? this: oThis,aArgs.concat(Array.prototype.slice.call(arguments)));};if (this.prototype) {// Function.prototype doesn't have a prototype propertyfNOP.prototype = this.prototype; }fBound.prototype = new fNOP();return fBound;};}