Always forget about the use of these two things and write them down to make a record.
Their functions are exactly the same, but the parameters passed in are different
apply
apply accepts two parameters. The first one formulates the pointing of this object in the function body, and the second one is a set with subscripts (the object can be traversed). The apply method passes the elements in this set as parameters to the called function:
var func = function(a, c, c){ alert([a,b,c]); //[1,2,3]}func.apply(null, [1,2,3]);call
The parameters passed in the call are not fixed. The same as apply is that the first parameter also represents this pointing in the function body. After the second parameter starts, each parameter is passed into the function in sequence:
var func = function(a, b, c){ alert([a,b,c]); //[1,2,3]}func.call(null, 1,2,3);call is a syntactic sugar of aplly. If the first parameter is null, this in the function body points to the host object, which is window in the browser.
Uses of call and apply
1. Change this point
The above example is
2. Function.prototype.bind
Simulate Function.prototype.bind
Function.prototype.bind = function(context){ var self = this; return function(){ return self.apply(context, arguments); }};var obj = { name: 'cxs'};var func = function(){ alert(this.name); //cxs}.bind(obj);fun();