JavaScript call and apply
If you want to learn the JavaScript language in depth, there is a very important knowledge point, which is to understand "call()" and " "apply()", sometimes when we look at the source code of others or some open source frameworks, these two methods also appear in large numbers. So what are these two methods for? what's the effect? The main content of this article is an in-depth discussion of these two methods. Before talking about these two methods, we still need to review a knowledge point that must be mastered in JavaScript, that is "this", because "call" and "apply" ” is closely related to “this”.
1. What is this
In object-oriented, such as Java, this represents a reference to the current object. In JavaScript, this is not fixed, but changes as its execution environment changes. To sum up: this always points to the object that calls its method. The usage of this generally has the following types, I will list them separately:
1. this is in the function
In this way In this method, I also call it "global function call". The code is as follows:
#Figure 1: global function call of this
It can be seen from the results that this inside the function test() points to the global object. In this example, the global object is window. In order to more fully prove that this is window in this example, the code is slightly adjusted as follows:
Figure 2: This global function call improvement
The results can further prove that the global name has been modified inside the function, because this inside the function refers to window.
Summary: For global function calls, this inside the function refers to the global object window, that is: this is the object where the calling function is located. In fact, this test() function is called by the global object window, so of course this inside the function refers to window.
2. this is in the constructor
The following is code analysis:
Figure 3: Constructor call of this
Analysis: We create an instance of an object through the new keyword, and we can find that the new keyword changes the pointer of this , point this this to the object person. Inside the constructor, we reassign this.name="HelloWorld" and do not change the value of the global variable name.
Summary: When declaring an instance object of a constructor, this inside the constructor will point to the new instance object, or in other words, this inside the constructor points to the newly created object itself.
3. Call
The following is code analysis:
Figure 4: Invocation of this object method
Summary: When When the person object calls the info() function, this inside the info function points to the person object. That is, when this appears in a method of an object, then this inside the method points to the object itself, that is to say, this points to the object that calls the function.
The above are the three situations where this appears. There is another position that I will talk about today, which appears in the call() and apply() methods.
2. What is the use of call and apply?
1. Problem introduction
Combined with the above example, let’s review and think about the several calling forms of functions in JavaScript. Look at the code:
Figure 5: Problem introduction code
Answer:
First method: direct call.
Person(); In this calling method, this inside the function points to the window
Second type: Constructor form call
var person = new Person(); In this method of call, this inside the function points to person
Summary: For the above two methods, it can actually be said that this inside the function represents the current object, but this inside the function in JavaScript will point to different objects according to the program.
#Then my question is: Can we manually modify the point of this?
Answer: Yes, use call or apply. This is what call and apply do-->change the pointer of this inside the function.
3. Thoughts caused by the code
First look at two programs and analyze them through the program
Procedure 1:
Figure 6: Triggering Questions and Thinking Procedure 1
Question: I Now I want to use this info method to print the p1 object. How to do it?
Option 1: Call the info function directly, that is: info(); through the above explanation, if you think about it carefully, it will definitely not work, because if called in this way, this inside the info function actually points to the window .
Option 2: Call through the object, that is, p1.info(); in fact, it does not work, because the p1 object does not have the info method at all, and the p1 object only has name and age attributes.
So how to solve the problem of program one? Look down, program two.
Procedure 2:
Figure 7: Problem-causing process 2
Through the illustration, we can find that we The p1 object adds a show attribute, and the value of this show attribute is actually the address of a function, which is a function object, and then printing can be achieved through p1.show(). This method can indeed achieve the function, but This method is completed by adding attributes to the p1 object. If there are still similar needs, should we add attributes to the p1 object to complete the needs? This will lead to The p1 object takes up more and more space, so the method is not elegant.
In response to the above problem, essentially we want to complete a printing of the current object by modifying the this pointer inside the info function, then we can do it without adding attributes To complete the function, this requires the use of call and apply
4. The use of call and apply
1, Function:
#Call the current function using the specified object.
2. Syntax:
call([thisObj[,arg1[, arg2[, [,.argN]]] ]])
apply(thisObj[,argArray])
3. Description:
## The functions of the two methods are exactly the same, the only difference is the parameters.
For the first parameter thisObj, the function is the same. It is used as an object representing the current object. To put it bluntly, it means who this points to when the function is executed.
For the second parameter, apply requires a parameter array to be passed in, that is to say, a series of parameters are composed into an array and passed in. For call, the hashed The parameter value is passed in. For example, the corresponding apply usage of func(thisObj, arg1, arg2, arg3...) is func(thisObj, [arg1, arg2, arg3...]). This article takes the call method as an example.
These two methods are methods in the Function object, because every object we define has this method.
The call method can be used to call a method on behalf of another object. The call method changes the object context of a function from the initial context to the new object specified by thisObj. If no thisObj parameter is provided, the Global object is used as thisObj.
4. Use call and apply to solve the problem of the above code
The code is as follows:## Figure 8: Use the call method to solve the problem
The above code solves the problem. Analysis: That is to say,
When the call method is called in the function, this inside the function will automatically point to the call method. The first parameter.In the above example, when info.call(p1) is executed, this inside the info function will automatically point to the p1 object, so of course the call method can be used to complete the printing of the p1 object.
The code is as follows: Figure 9: In-depth discussion of the call method Analyze the above code and why it prints out " "HelloWorld little coder", the cat object obviously does not have an info method at all. The key to this answer is the line of code Person.call(cat). Think carefully about what happened. When the call method is called At this time, this inside the function Person has actually automatically pointed to the cat object, which is equivalent to executing the following two lines of code for the cat object: and then rewriting the original The name attribute in the cat object changed the name from "Little Cat" to "HelloWorld Little Coder", and obtained a new info method (it can be understood that it is equivalent to adding an info attribute to the cat object). So of course the cat object can call the info method, so the result is "HelloWorld little coder". The use of apply has the same function as call, and the usage method is also very similar. I will not give an example here
The above is the detailed content of JavaScript call and apply. 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).

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
