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!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools

Atom editor mac version download
The most popular open source editor