search
HomeWeb Front-endJS TutorialJavaScript call and apply

JavaScript call and apply

Mar 24, 2018 pm 05:23 PM
applyjavascript

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:

JavaScript call and apply

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

JavaScript call and apply

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:

JavaScript call and apply

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

in the method of the object

The following is code analysis:

JavaScript call and apply

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:

JavaScript call and apply

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:

JavaScript call and apply

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:

JavaScript call and apply

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:

JavaScript call and apply## 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.

5. Let’s look at a more complicated example

The code is as follows:

JavaScript call and apply

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:

JavaScript call and apply

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!

Statement
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
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

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

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

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.

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

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.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

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