Explain the usage of apply and call in js in detail

  • 2021-07-06 10:04:12
  • OfStack

Preface

Both call and apply exist to change the context of context when a function is running, in other words, to change the direction of this inside the function body.
The effects of call and apply2 are completely identical, but the way of accepting parameters is not quite identical.

Method definition
apply
Function.apply(obj,args) Method can take two parameters:

obj: This object will replace the this object in the Function class

args: This is an array or class array, and the apply method passes the elements of this collection as arguments to the called function.

call

The first parameter of the call method is the same as that of the apply method, except that the second parameter is a parameter list

When we pass null or undefined as the first argument in non-strict mode, this in the function body points to the default host object, and window in the browser


var test = function(){
  console.log(this===window);
}
test.apply(null);//true
test.call(undefined);//true

Usage

Ways to "hijack" others

The logName method in foo will then be referenced by bar, which points to bar


var foo = {
  name:"mingming",
  logName:function(){
    console.log(this.name);
  }
}
var bar={
  name:"xiaowang"
};
foo.logName.call(bar);//xiaowang

Implement inheritance


function Animal(name){   
  this.name = name;   
  this.showName = function(){   
    console.log(this.name);   
  }   
}   

function Cat(name){  
  Animal.call(this, name);  
}   

var cat = new Cat("Black Cat");   
cat.showName(); //Black Cat

In actual development, it is often encountered that this points to scenes that have been inadvertently changed.
There is a local fun method. When fun is called as a normal function, this inside fun points to window, but we often want it to point to the # test node, as shown in the following code:


window.id="window";
document.querySelector('#test').onclick = function(){
  console.log(this.id);//test
  var fun = function(){
    console.log(this.id);
  }
  fun();//window
}

Using call, apply, we can easily solve this problem


window.id="window";
document.querySelector('#test').onclick = function(){
  console.log(this.id);//test
  var fun = function(){
    console.log(this.id);
  }
  fun.call(this);//test
}

Of course you can do this, but in strict mode of ECMAScript 5, this in this case has been specified not to point to global objects, but undefined:


window.id="window";
document.querySelector('#test').onclick = function(){
  var that = this;
  console.log(this.id);//test
  var fun = function(){
    console.log(that.id);
  }
  fun();//test
}

function func(){
  "use strict"
  alert ( this );  //  Output: undefined
}
func();

Other usages

Class array

Here, objects that meet the following conditions are called class arrays

1. Have the length attribute

2. Store data indexed

3. push, pop, etc. without arrays

Common class arrays are arguments, NodeList!


(function(){
  Array.prototype.push.call(arguments,4);
  console.log(arguments);//[1, 2, 3, 4]
})(1,2,3)

This goes into push1 4 in arguments

Array.prototype.push Page can implement two combinations of numbers and

Similarly, the push method does not provide push1 arrays, but it does provide push (param1, param, … paramN), so it is also possible to replace this array with apply, namely:


var arr1=new Array("1","2","3"); 
var arr2=new Array("4","5","6"); 
Array.prototype.push.apply(arr1,arr2); 
console.log(arr1);//["1", "2", "3", "4", "5", "6"]

It can also be understood that arr1 calls the push method, and the parameters are the collection of numbers assembled into parameter lists through apply.

For example, I want to find the maximum value in the class array


(function(){
  var maxNum = Math.max.apply(null,arguments);
  console.log(maxNum);//56
})(34,2,56);

Judgment type


var foo = {
  name:"mingming",
  logName:function(){
    console.log(this.name);
  }
}
var bar={
  name:"xiaowang"
};
foo.logName.call(bar);//xiaowang
0

The above is the whole content of the usage summary of apply and call. Welcome to actively leave a message to participate in the discussion, and hope that this article will be helpful for everyone to learn javascript.


Related articles: