Detailed introduction of functions apply() and call()
This article brings you a detailed introduction to the functions apply() and call(). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Introduction to apply and call in functions
When it comes to apply and call, we must first talk about their origins with functions
Javascript functions are both objects
It is no different from other javascript objects. And each function contains two non-inherited methods apply() and call(), both of which can indirectly call the function
For example:
function f() { console.log(1); } f.call(); //1 f.apply(); //1
And these two methods Each method allows the display of the this value after the specified function call.
Regarding the value of this, since the value of this is confirmed when entering the execution context stage, the value of this is confusing. But we can explicitly specify the required this value when the function is called through apply() and call().
So what are the apply and call methods used for?
Any function can be assigned this value when called and called as a method of the object pointed to by this.
That means any function can be called by any object. This is the ultimate goal of the apply and call methods.
Let us take a usage example to understand
function Animal() {}; Animal.prototype = { constructor: Animal, other: function() { console.log('这是一只' + this.name); } } var animal = new Animal(); //定义一个对象 var dog = { name: '狗' }; //我的dog对象想使用Animal函数的other方法怎么办,使用call或apply animal.other.call(dog); animal.other.apply(dog);
In the above, we use animal.other (think about what it is, yes, it is essentially a function) as the dog object method call. Next, we use some practical ones.
//设置一个类数组对象 var arrLike = { 0: '我是apply', 1: '我是call', length: 2 } //将Arrar的slice函数的this显式指向arrLike,并将0作为参数传入slice函数 var newArr = Array.prototype.slice.call(arrLike, 0); //等价于 arrLike.slice(0); console.log(newArr);
For apply() and cal(), all the first arguments passed to them will become the value of this, Even if the passed arguments Is the original value
, null, undefined. And if the first actual parameter passed in is undefined or null, it will be replaced by the global object in ES3 and non-strict mode, and other original values will be replaced by the corresponding wrapper object
.
In layman's terms, Js doesn't care what the first parameter of apply/call is. The function will still be called, but whether the call will report an error is another matter.
var str = '我是一个函数'; //将字符串传入,但是String对象无法调用slice属性 报错 Array.prototype.pop.call(str);
In order to remember these two methods deeply and when to use these two methods, list some common usages
First of all, for now, the performance difference between these two methods Almost ignored, so how to use them?
apply() method is suitable for passing in the second parameter in order and the parameters are uncertain. Use the apply method, such as the arguments of a function. This array-like object is very suitable for passing as a parameter.
function A(a, b, c) { console.log(a, b, c); } var fn = (function(func, b, c) { var args = arguments; return () => { func.apply(null, args); } }(A, 66, 99)); fn();
Another example is to append elements to the array
var arr1 = [1, 2, 3]; var arr2 = [66, 99, 131]; Array.prototype.push.apply(arr1, arr2); console.log(arr1);
Similarly pass the arr2 array as a parameter.
For unordered parameters that are not related to each other, use call()
to obtain the maximum and minimum values of the array
var arr = [0, 1, 2, 3, 4]; //获取最大数 var max1 = Math.max.apply(Math, arr), max2 = Math.max.call(Math, 0, 1, 2, 3, 4), //获取最小数 min1 = Math.min.apply(Math, arr), min2 = Math.min.call(Math, 0, 1, 2, 3, 4); console.log(max1, max2, min1, min2);
arr itself does not have a Math method, but we can use call or apply to use its method
Determine the specific type of the object
//验证对象的具体类型 var arr = []; var type = Object.prototype.toString.call(arr); console.log(type);// [object Array]
Obtained when using typeof The results are all Object, and it is impossible to determine which type they are. So you can use Object.prototype.toString.call() to get the specific type. Of course, the premise is that the toSting() method has not been overridden
Convert the array-like object into a real array, usually we use Array.prototype.slice.call() to convert
var arrLike = { length: 3, 0: '值1', 1: '值2', 2: '值3' } var newArr = [].__proto__.slice.call(arrLike); var type = Object.prototype.toString.call(newArr); console.log(newArr, type); //[ '值1', '值2', '值3' ] '[object Array]'
Of course, splice,concat can also convert array-like objects into arrays
.
Here is a popularization of array-like objects
.
Access elements through indexes and have the length attribute
In other words, two conditions need to be met, 1. Use serial numbers to define attributes, 2. Have the length attribute, the attribute value is the number of elements
When using serial numbers When defining attributes, it is recommended to define attributes in order starting from 0. Otherwise, the array element will be empty
var arrLike = { length: 3, 0: '值1', 1: '值2', 3: '值3' } var newArr = [].__proto__.slice.call(arrLike); var type = Object.prototype.toString.call(newArr); console.log(newArr, type); //[ '值1', '值2', empty] [object Array]
This article has ended here. For more exciting content, you can pay attention to the JavaScript Video Tutorial column on the PHP Chinese website!
The above is the detailed content of Detailed introduction of functions apply() and call(). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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.

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

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

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

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
