Home > Web Front-end > JS Tutorial > Usage of apply and call in js

Usage of apply and call in js

不言
Release: 2018-05-05 16:02:52
Original
1110 people have browsed it

This article mainly introduces the usage of apply and call in js. It has certain reference value. Now I share it with everyone. Friends in need can refer to

The prototype definition of Function in ECAMScript3 There are two methods, they are Function.prototype.call and Function.prototype.apply. This article introduces the usage of apply and call in detail. You can refer to it if necessary.

Preface

call and apply both exist to change the context that is, the context when a function is running , In other words, it is to change the pointer of this inside the function body.
call and apply have exactly the same function, but the way they accept parameters is different.

Method definition
apply
Function.apply(obj,args)The method can receive two parameters:

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

args: This is an array or array-like, apply method Pass the elements of this collection as arguments to the called function.

call

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

In non-strict mode, when the first parameter is passed as null or undefined, this in the function body will point to the default host object. In the browser It is window

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

Usage

"Hijacking" method of others

At this time, the logName method in foo will be referenced by bar, this points to bar

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

Implementing 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
Copy after login

In practice During development, we often encounter scenarios where this pointer is inadvertently changed.
There is a local fun method. When fun is called as a normal function, fun internal this points to window, but we often want it to point to the #test node, see 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
}
Copy after login

Usecall,applyWe 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
}
Copy after login

Of course you can also do this, but in ECMAScript In the strict mode of 5, this in this case has been stipulated not to point to the global object, but to 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
}
Copy after login

function func(){
  "use strict"
  alert ( this );  // 输出:undefined
}
func();
Copy after login

Other usage

##Array-like

Here, objects that meet the following conditions are called array-like


1. Have the length attribute


2. Store data by index


3. Push, pop and other methods that do not have arrays


Common class arrays include

arguments, NodeList!

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

In this way, push a 4 into

arguments

Array.prototype.push The page can realize the merger of two arrays

The same push method does not provide push an array, but it provides

push(param1, param,...paramN) So you can also replace this array through apply, that is:

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"]
Copy after login

can also be understood this way,

arr1 calls the push method, and the parameter is the number passed to apply The assembly is replaced by a set of parameter lists.

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

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

Judge type

console.log(Object.prototype.toString.call(123)) //[object Number]
console.log(Object.prototype.toString.call('123')) //[object String]
console.log(Object.prototype.toString.call(undefined)) //[object Undefined]
console.log(Object.prototype.toString.call(true)) //[object Boolean]
console.log(Object.prototype.toString.call({})) //[object Object]
console.log(Object.prototype.toString.call([])) //[object Array]
console.log(Object.prototype.toString.call(function(){})) //[object Function]
Copy after login

Related recommendations:

url, href, src Using

instance in JS to parse this

in JS

The above is the detailed content of Usage of apply and call in js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template