Usage of call(),apply()

The call() method calls a function using a specified this value and one or more parameters given separately.
The apply() method calls a function with a given value of this and the parameters provided as an array (or similar array object).
The bind() method creates a new function. When the bind() is called, this of the new function is specified by the first parameter of the bind, and the rest of the parameters are used as parameters of the new function.

The similarities of the three are as follows:
1. They are used to change the direction of this object of a function.
2. The first parameter is the object to which this points.
3. All parameters can be used to transmit data.

Note: The call() method acts like the apply() method, except that the call() method accepts a list of parameters, while the apply() method accepts an array of parameters.

Syntax:
call: fun.call(thisOject, arg1, arg2, ...)
apply: func.apply(thisOject, [argsArray])
bind: function.bind(thisOject[,arg1[,arg2[, ...]]])

A small example to explain the difference between the three

function fn1(height){console.log(`Full name:${this.name},Age: ${this.age},Height: ${height}`)}
var obj = {name:'Li Si',age:35}

fn1(180); // Name: undefined, age: undefined, height: 180

// call
fn1.call(obj,180); // Name: Li Si, age: 35, height: 180

// apply
fn1.apply(obj,[180]); // Name: Li Si, age: 35, height: 180

// bind
fn1.bind(obj,180)(); // Name: Li Si, age: 35, height: 180

1.Function.prototype.call()

Syntax: fun. call (this object, arg1, arg2,...)
Parameters:
thisOject: The value of this specified when the fun function runs.

if(thisOject== undefined|null) {this = window}
if(thisOject== number|boolean|string){ this == new Number()|new Boolean()| new String()}

List of parameters specified by arg1, arg2,....

call() allows assignment and invocation of functions/methods belonging to one object for different objects.
call() provides a new this value to the function/method currently being called. Inheritance can be achieved using call: write a method and then let another new object inherit it (instead of writing the method again in the new object).

Example:

Achieving inheritance:

/* Without inheritance, fn2 uses attributes in fn1 */
function fn1(name){this.name =name;this.sex ='female';}
function fn2(){this.age = 20;}

var f2 = new fn2();
console.log(f2.name);'// undefined
console.log(f2.sex);'// undefined

/* Inheritance of fn1 with call */
function fn1(name){this.name =name;this.sex ='female';}
function fn2(){fn1.call(this,'Zhang San');this.age = 20;}

var f2 = new fn2();
console.log(f2.name); //"Zhang three"
console.log(f2.sex); //"Female"

'this'implements the calling function and specifies the context

function fn1(height){console.log(`Full name:${this.name},Age: ${this.age},Height: ${height}`)}
var obj = {name:'Li Si',age:35}

fn1(180); // Name: undefined, age: undefined, height: 180
fn1.call(obj,180); // Name: Li Si, age: 35, height: 180

2.Function.prototype.apply()

Apply is very similar to call(), but the difference is how parameters are provided. Apply uses an array of parameters instead of a list of parameters. Apply can use array literal s, such as fun. apply (this, ['eat','bananas']), or array objects, such as fun. apply (this, new Array ('eat','bananas').

For example, the above case uses apply's words:

function fn1(height){console.log(`Full name:${this.name},Age: ${this.age},Height: ${height}`)}
var obj = {name:'Li Si',age:35}

fn1(180); // Name: undefined, age: undefined, height: 180
fn1.call(obj,180); // Name: Li Si, age: 35, height: 180

// apply
fn1.apply(obj,[180]); // Name: Li Si, age: 35, height: 180

Syntax: func. apply (this object, [argsArray])
Parameters:
thisOject: Optional. This value is used when the func function runs. Note that this may not be the actual value that this method sees: if the function is in a non-strict mode, null or undefined will be automatically replaced by pointing to the global object, and the original value will be wrapped.
Args Array: Optional. An array or class array object in which the array elements are passed to the func function as separate parameters. If the value of this parameter is null or undefined, it means that no parameters need to be passed in. Class array objects can be used starting with ECMAScript 5. See the bottom of this article for browser compatibility.

Expand
apply an array to another array

var arr1 = ['Zhang San', 'Li Si'];
var arr2 = [0, 1, 2];
arr1.push.apply(arr1, arr2);
console.log(arr1 ); // [Zhang San, Li Si, 0, 1, 2]

Use apply and built-in functions

var arr = [4, 5, 1, 2, 6];

Math.max(...arr); // 6
Math.max.apply(null, arr);  // 6

But beware: if apply is called in the above way, there is a risk of exceeding the parameter length limit of the JavaScript engine. When you pass in many parameters (such as 10,000) to a method, it's very likely that you'll cross the boundary, depending on the different JavaScript engines.

 

 

 

 

 

 

 

 

 

 

 

 

Keywords: Javascript REST ECMAScript

Added by RON_ron on Wed, 18 Sep 2019 13:13:08 +0300