js apply, call learning

The call and apply in js are mainly to implement schemes like inheritance in java.

The calling method of call:
obj.call(thisObj, arg1, arg2,...);
Call description:
The function of this method is to bind obj (ie this) to thisObj, so that thisObj has the properties and methods of obj; and Execute the function immediately.

Such as:
function add(a, b) { return a + b;}

function sub( a, b) { return a - b;}

add.call(sub, 5, 3); //Let sub add the add method and immediately Execute the add method, the result: 8

The calling method of apply:
obj.apply(thisObj, [arg1, arg2,..]);
Calling description:
The function of this method is the same as that of call, except that the parameter becomes an array object, and the array is received .

## call, apply call the method of the native object
var a = {0: 1, 1: "youngstream", length: 2};
a.slice(); //Error will be reported because slice does not define
Array.prototype.slice. call(a); //You will get [1, "youngstream"], which means that the a object has the ability of the slice method of Array.

Call and apply can also be used for the implementation of inheritance. The specific scheme is similar to the above code!

Reference blog: http://www.cnblogs.com/52fhy/p/5118877.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326480593&siteId=291194637