Indirect call (call, apply) and binding (bind) of ES5 functions

The first argument of call() and apply() is the context of the function call, and a reference to it is obtained through this in the function body.

call() separates the arguments with commas; apply() puts the arguments into an array, array-like object.

function hello(roleA,roleB){
    console.log(this.name,roleA,roleB);
}

var turtles = {
    name :   'Endure the Turtle'
};

hello.call(turtles,'Leo','Raph');

hello.apply(turtles,['Mikey','Don']);

bind() is a new method in ECMAScript5, and its main function is to bind a function f to an object o. This method will return a new function g, and calling the new function g will call the original function f as a method of o.

var saints =
    name : 'Saint Seiya'
};

var hello2 = hello.bind (saints);
hello2 ( 'Mu', 'canon' );

var hello3 = hello.bind(saints,'Aioria');
hello3('Shaka');

Guess you like

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