Home Web Front-end JS Tutorial What are the uses of the call() method and apply() method in Javascript? (Code attached)

What are the uses of the call() method and apply() method in Javascript? (Code attached)

Aug 01, 2018 pm 04:35 PM
javascript

The apply() method and call() method in JavaScript are methods of the Function object. Each Function object will have an apply() method and a call() method. Then, the apply() method and the call() method are in What is its usage and function in JavaScript? This article will talk about the usage of apply() method and call() method.

The syntax of apply() method and call() method:

/*apply()方法*/
function.apply(thisObj[, argArray])
/*call()方法*/
function.call(thisObj[, arg1[, arg2[, [,...argN]]]]);
Copy after login

Function: Borrow the method of another object without copying. (Can be used to call a method instead of another object, changing the object context of a function from the initial context to the new object specified by thisObj)

apply() method and call() method Basic usage:

function add(a,b){
  return a+b;  
}
function sub(a,b){
  return a-b;  
}
var a1 = add.apply(sub,[4,2]);  //sub调用add的方法
var a2 = sub.apply(add,[4,2]);
alert(a1);  //6     
alert(a2);  //2

/*call的用法*/
var a1 = add.call(sub,4,2);
Copy after login

apply() method and call() method Implement inheritance:

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

function Cat(name){
  Animal.apply(this,[name]);    
}

var cat = new Cat("咕咕");
cat.showName();

/*call的用法*/
Animal.call(this,name);
Copy after login

apply() method and call() method Implement multiple inheritance:

    function Class10(){
      this.showSub = function(a,b){
            alert(a - b);
        }   
    }
    
    function Class11(){
      this.showAdd = function(a,b){
            alert(a + b);
        }  
    }
    
    function Class12(){
      Class10.apply(this);
      Class11.apply(this);   
      // Class10.call(this);
      //Class11.call(this);  
    }
    
    var c2 = new Class12();
    c2.showSub(3,1);    //2
    c2.showAdd(3,1);    //4
Copy after login

The function of the Call() method: change the pseudo array into a real array

The pseudo array is a json object containing the length attribute It is not a real array. In fact, it is simulating a collection (describing collection data)

For example:

var json = {1:’苹果’,2:’香蕉’,3:’菠萝’,length:3}
Var arr = [‘苹果’,’香蕉’,’菠萝’]
Copy after login

His characteristics:

1. All keys It is 1, 2, 3, 4, 5
2. It contains a length attribute

How to convert a pseudo array into a real array

/*我们通过如下方式将其转换成数组*/
/*slice:截取数组,返回的还是数组,这里截取全部*/
var domNodes=Array.prototype.slice.call(divs);
/*这样domNodes就可以应用Array下所有方法*/
Copy after login

apply() Method usage tips:

1. Math.max can achieve the largest item in the array:

Because Math.max does not support Math.max ([param1,param2]) is an array, but it supports Math.max(param1,param2...), so you can solve var max=Math.max.apply(null,array) according to the characteristics of apply, so that You can easily get the largest item in an array (apply will convert an array into a parameter-by-parameter method and pass it to the method).

When calling this block, the first parameter is given to null. This is because there is no object to call this method. I just need to use this method to help me calculate and get the returned result, so I pass it directly. A null passes.

You can also use this method to get the minimum item in the array: Math.min.apply(null,array)

2. Array.prototype.push can achieve two Merging of arrays

The same push method does not provide push to an array, but it provides push(param1,param2...paramN). You can also use apply to convert this array, that is:

   var arr1=new Array("1","2","3");
    var arr2=new Array("4","5","6");
    Array.prototype.push.apply(arr1,arr2);    
    //得到合并后数组的长度,因为push就是返回一个数组的长度
Copy after login

It can also be understood that arr1 calls the push method, and the parameter is an array converted into a collection of parameter lists through apply

Usually under what circumstances, you can use apply similar to Math. Special usages such as max: Generally, the target function only requires n parameter lists and does not receive an array. This problem can be solved cleverly by applying.

Recommended related articles:

Comparison of the use of call method and apply method in JavaScript_Basic knowledge

call and apply method in JavaScript A brief discussion on _javascript skills

The above is the detailed content of What are the uses of the call() method and apply() method in Javascript? (Code attached). For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles