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

Usage of apply and call in js

不言
不言Original
2018-05-05 16:02:521112browse

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

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

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

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
}

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
}

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
}

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

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)

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"]

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);

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]

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!

Statement:
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