Detailed explanation of the use of Js apply() (including code)
The following is the use of Js apply() that I compiled for everyone. Interested students can take a look.
Js apply method detailed explanation
When I first saw the javascript functions apply and call, they were very blurry and I couldn’t understand them. I recently read them online After reading some examples of the apply method and call in some articles, I finally got a glimpse of them. Here I will make the following notes and hope to share them with you. If there is anything wrong or the explanation is not clear, I hope readers can give me some comments. , in order to improve together..
Mainly I want to solve a few problems:
1. What is the difference between apply and call
2. Under what circumstances should apply be used? , when to use call
3. Other clever uses of apply (generally under what circumstances can apply be used)
I first found the definitions of apply and call from the Internet, and then used Examples are provided to explain the meaning of these two methods and how to use them.
Apply: The method can hijack the method of another object and inherit the properties of another object.
Function.apply(obj, args) method can receive two parameters
obj: This object will replace this object in the Function class
args: This is an array, which will be passed to Function as a parameter (args--> arguments)
call: The meaning is the same as apply, but the parameter list is different.
Function.call(obj,[param1[,param2[,…[,paramN]]] ])
obj: This object will replace this object in the Function class
params: This is a parameter list
1.apply示例: <script type="text/javascript"> /*定义一个人类*/ function Person(name,age) { this.name=name; this.age=age; } /*定义一个学生类*/ functionStudent(name,age,grade) { Person.apply(this,arguments); this.grade=grade; } //创建一个学生类 var student=new Student("qian",21,"一年级"); //测试 alert("name:"+student.name+"\n"+"age:"+student.age+"\n"+"grade:"+student.grade); //大家可以看到测试结果name:qian age:21 grade:一年级 //学生类里面我没有给name和age属性赋值啊,为什么又存在这两个属性的值呢,这个就是apply的神奇之处. </script>
Analysis: Person.apply(this,arguments);
this: When creating an object, it represents the student at this time
arguments:是一个数组,也就是[“qian”,”21”,”一年级”];
In other words, in layman’s terms: use student to execute the content in the Person class, and this exists in the Person class .name, etc., thus creating the attributes into the student object
2.call example
In the Student function, you can modify the apply to the following:
Person.call(this,name,age);
This is ok
3. When to use apply and when to use call
When giving object parameters, if the parameter is in the form of an array, such as apply The parameter arguments is passed in the example. This parameter is of array type, and the list of parameters is consistent when calling Person (that is, the first two digits of the parameter lists of Person and Student are consistent). You can use apply. If my Person's parameter list is like this (age, name), and Student's parameter list is (name, age, grade), so it can be implemented with call, that is, directly specifying the position of the corresponding value in the parameter list (Person.call (this,age,name,grade));
4.Some other clever uses of apply
Careful people may have noticed that when I call the apply method, the first The parameter is an object (this), and the second parameter is an array collection.
When calling Person, what he needs is not an array, but why did he give me an array? I can still parse the array into an array. A parameter,
This is a clever use of apply. It can convert an array into a parameter list by default ([param1, param2, param3] is converted into param1, param2, param3). If we let It may take a while to use a program to convert each item of the array into a list of parameters. With the help of this feature of apply, we have the following efficient method:
a) Math.max can achieve the largest item in the array
Because the Math.max parameter does not support Math.max([param1, param2]), which is an array
But it does Math.max(param1, param2, param3...), so you can solve it based on the characteristics of apply just now var max=Math.max.apply(null, array), so you can easily get the largest item in an array
(apply will convert an array into a parameter and pass it to the method one by one)
这块在调用的时候第一个参数给了一个null,这个是因为没有对象去调用这个方法,我只需要用这个方法帮我运算,得到返回的结果就行,.所以直接传递了一个null过去
b)Math.min 可以实现得到数组中最小的一项
同样和 max是一个思想 var min=Math.min.apply(null,array);
c)Array.prototype.push 可以实现两个数组合并
同样push方法没有提供push一个数组,但是它提供了push(param1,param,…paramN) 所以同样也可以通过apply来装换一下这个数组,即:
vararr1=new Array("1","2","3"); vararr2=new Array("4","5","6"); Array.prototype.push.apply(arr1,arr2);
也可以这样理解,arr1调用了push方法,参数是通过apply将数组装换为参数列表的集合.
通常在什么情况下,可以使用apply类似Math.min等之类的特殊用法:
一般在目标函数只需要n个参数列表,而不接收一个数组的形式([param1[,param2[,…[,paramN]]]]),可以通过apply的方式巧妙地解决这个问题!
5.总结:
一开始我对apply 非常的不懂,最后多看了几遍,自己多敲了几遍代码,才明白了中间的道理,所以,不管做什么事情,只要自己肯动脑子,肯动手敲代码,这样一个技术就会掌握…
还有比如第四部分得内容,巧妙的解决了实实在在存在的问题,这个肯定不是一个初学者能想到的解决方案(这个也不是我自己想的),没有对编程有一定认识的不会想到这个的,还是一句话,多积累,多学习,提升自己的能力和对编程思想的理解能力才是最关键!
上面是我整理给大家的Js apply()使用,希望今后会对大家有帮助。
相关文章:
The above is the detailed content of Detailed explanation of the use of Js apply() (including code). For more information, please follow other related articles on the PHP Chinese website!

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.


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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
