Understanding Array. prototype. slice. apply, array. prototype
1. First, we all understand that there are three methods to change this reference in js: call (), apply (), bind ();
2. the bind method is to change the this reference in the function and will not be described in a simple way;
3. As for the call () and apply () methods, the difference is that the former is an input parameter of an indefinite length and the latter is an array. The following describes how to use the apply method;
Principle:
We know that js has an array object type, such {0:1,length:1}Or DOM object or arguments object;
An array is only a special object. Its key is an integer (, 2...) arranged in order by default ...), therefore, the array does not need to specify a key name for each element, and each member of the object must specify a key name.
Therefore, arrays in JavaScript can be viewed as such objects.
var array = [1, 2, 3]; var obj = { 0: 1, 1: 2, 2: 3, length:3 }
Note that this length attribute is very important. With length, you can traverse this object like an array.
Then we can implement a simple slice method,
function slice(start, end) { var array = []; start = start ? start : 0; end = end ? end : this.length; for (var i = start, j = 0; i < end; i++, j++) { array[j] = this[i]; } return array;}
Example: Array. prototype. slice. apply ({, length: 1 });
Use apply to point this in the slice method to this object and traverse and generate a new array object.
Note:
1. when using apply, note that apply or call only switches the call of this in the function, but the method to be executed is still the method on the original object, even if you are in Array. prototype. slice. the obj of call (obj) overwrites the slice method, and the slice Method on the Array is still executed;
2. Because the apply method (or call method) can be bound to the object where the function is executed, but the function is executed immediately, the binding statement must be written in a function. We recommend that you use the bind method when changing this point using the function.
3.
Every time the bind method runs, a new function is returned, which produces some problems. For example, when you listen to an event, you cannot write it as follows.
element.addEventListener('click', o.m.bind(o));
The code above indicates an anonymous function generated by binding the click event to the bind method. As a result, the binding cannot be canceled. Therefore, the following code is invalid.
element.removeEventListener('click', o.m.bind(o));
The correct method is as follows:
var listener = o.m.bind(o);element.addEventListener('click', listener);// ...element.removeEventListener('click', listener);