Call and apply
obj.call(thisObj, arg1, arg2, ...);obj.apply(thisObj, [arg1, arg2, ...]);
Both of these functions are obj bound to (that is, this) to thisObj , this thisObj time have obj the properties and methods. Or, thisObj "inherited" obj properties and methods. Functions are executed immediately after binding.
The only difference is that apply accepts an array parameter, and call accepts a continuous parameter.
function add(j, k){ return j+k;}function sub(j, k){ return j-k;}
We run on the console:
add(5,3); //8add.call(sub, 5, 3); //8add.apply(sub, [5, 3]); //8sub(5, 3); //2sub.call(add, 5, 3); //2sub.apply(add, [5, 3]); //2
Methods to invoke native objects
Example:
var a = {0:1, 1:"yjc", length: 2}; a.slice(); //TypeError: a.slice is not a functionArray.prototype.slice.call(a);//[1, "yjc"]
Object a resembles an array, but does not have methods such as the slice of an array. The slice method can be called when using call binding.
Implementing inheritance
With call and apply, we can implement object inheritance. Example:
var Parent = function(){ this.name = "yjc"; this.age = 22;}var child = {};console.log(child);//Object {} ,空对象Parent.call(child);console.log(child); //Object {name: "yjc", age: 22}
The above implements the inheritance of the object.
Use of BIND
obj.bind(thisObj, arg1, arg2, ...);
When you bind obj to Thisobj, Thisobj has the properties and methods of obj. Unlike call and apply, bind is not executed immediately after binding.
Same as Add () and sub ():
add.bind(sub, 5, 3); //不再返回8add.bind(sub, 5, 3)(); //8
If the first parameter of BIND is null or undefined, it is equal to binding this to the global object.
How to understand and skillfully use the JS in the call and apply?