obj.call(thisObj, arg1, arg2, ...);obj.apply(thisObj, [arg1, arg2, ...]);
Both have the same effect, which is to bind obj (this) to Thisobj, when Thisobj has the properties and methods of obj. Or, Thisobj "inherits" the properties and methods of obj.
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
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.
The difference between call apply in JavaScript