Home Web Front-end JS Tutorial In-depth understanding of the difference between apply() and call() methods in javascript_javascript skills

In-depth understanding of the difference between apply() and call() methods in javascript_javascript skills

May 16, 2016 pm 03:05 PM
javascript

If you have never been exposed to dynamic languages, it will be a magical and weird feeling to understand JavaScript with the way of thinking of compiled languages, because things that are consciously impossible often happen, and even feel unreasonable. If you are learning When you encounter this feeling in the process of JavaScript, a free and ever-changing language, then from now on, please put down your "prejudice", because this is definitely a new continent for you, and let JavaScript slowly melt away from the past. Set a solidified programming consciousness and inject new vitality!

Okay, let’s get down to business. First, understand the dynamically changing runtime context characteristics of JavaScrtipt. This feature is mainly reflected in the use of the apply and call methods.

The difference between apply and call is just one sentence,

foo.call(this, arg1,arg2,arg3) == foo.apply(this, arguments)==this.foo(arg1, arg2, arg3)


call and apply are both methods of Function.prototype, which are implemented internally by the JavaScript engine. Because they belong to Function.prototype, each Function object instance, that is, each method has call and apply attributes. Since they are attributes of the method , then their use is of course targeted at methods. These two methods are easy to confuse, because they have the same function, but they are used in different ways.

Same points: The two methods have exactly the same effect

Difference: The parameters passed by the method are different

Then what is the function of the method and what are the parameters passed by the method?

Let’s analyze the above foo.call(this, arg1, arg2, arg3).

foo is a method, this is the context-sensitive object when the method is executed, arg1, arg2, arg3 are the parameters passed to the foo method. The so-called context-sensitive objects when the method is executed here, if you have the basis of object-oriented programming, it is very It’s easy to understand, it’s this.

in the object after the class is instantiated.

In JavaScript, code always has a context object, and the code processes this object. The context object is represented by the this variable, and this this variable always points to the object where the current code is located.

In order to better understand what this is, let’s give an example.

/创建一个A类
function A(){
//类实例化时将运行以下代码
//此时的执行上下文对象就是this,就是当前实例对象
this.message = “message of a”;
this.getMessage = function(){
<SPAN style="WHITE-SPACE: pre">	</SPAN>return this.message;
<SPAN style="WHITE-SPACE: pre">	</SPAN>}
}
//创建一个A类实例对象
var a = new A();
//调用类实例getMessage方法获得message值
alert(a.getMessage());
//创建一个B类
function B(){
this.message = ”message of b”;
this.setMessage = function(msg){
<SPAN style="WHITE-SPACE: pre">	</SPAN>this.message = msg;
<SPAN style="WHITE-SPACE: pre">	</SPAN>}
}
//创建一个B类实例对象
var a = new B();
Copy after login

It can be seen that classes A and B both have a message attribute (a member in object-oriented terms). A has a getMessage method to get the message, and B has a setMessage method to set the message. The power of call is shown below.

//给对象a动态指派b的setMessage方法,注意,a本身是没有这方法的!
b.setMessage.call(a, “a的消息”);
//下面将显示”a的消息”
alert(a.getMessage());
//给对象b动态指派a的getMessage方法,注意,b本身也是没有这方法的!
Copy after login

This is the power of dynamic language JavaScript call!

It is simply "made out of nothing". The method of the object can be assigned arbitrarily, but the object itself has never had such a method. Note that it is assigned. In layman's terms, the method is lent to another object to complete the task. In principle The context object changes when the method is executed.

So b.setMessage.call(a, "a's message"); is equivalent to using a as the execution context object to call the setMessage method of the b object, and this process has nothing to do with b, and the effect is equivalent to a.setMessage(“a’s message”);

Because apply and call have the same effect, it can be said

The function of call and apply is to borrow other people’s methods to call, just like calling your own.

Okay, after understanding the similarities between call and apply--after their functions, let's take a look at their differences. After reading the above examples, I believe you probably know it.

From b.setMessage.call(a, "a's message") is equivalent to a.setMessage("a's message"), it can be seen that "a's message" is passed as a parameter in call,

So how does it express in apply? It’s not clear to explain directly. Apply needs to be combined with the application scenario to make it clear at a glance. Let’s design an application scenario:

function print(a, b, c, d){
alert(a + b + c + d);
}
function example(a, b , c , d){
//用call方式借用print,参数显式打散传递
print.call(this, a, b, c, d);
//用apply方式借用print, 参数作为一个数组传递,
//这里直接用JavaScript方法内本身有的arguments数组
print.apply(this, arguments);
//或者封装成数组
print.apply(this, [a, b, c, d]);
}
//下面将显示”背光脚本”
example(”背” , “光” , “脚”, “本”);
Copy after login

In this scenario, in the example method, a, b, c, d are used as parameters passed by the method. The methods use apply and call respectively to borrow the print method to call,

The last sentence is because the example method is called directly, so the context object this in this method is the window object.

So, except for the first parameter of the call and apply methods, which is the context object during execution, the other parameters of the call method will be passed to the borrowed method as parameters in turn, while apply has only two parameters, the second parameter Passed as an array. So it can be said as

The difference between the call and apply methods is that starting from the second parameter, the call method parameters will be passed to the borrowed method as parameters in turn, while apply directly puts these parameters into an array and then passes them, and finally the parameter list of the borrowed method It’s the same.


Application scenarios:

When the parameters are clear, you can use call. When the parameters are unclear, you can use apply to combine arguments

//例
print.call(window, “背” , “光” , “脚”, “本”);
//foo参数可能为多个
function foo(){
<SPAN style="WHITE-SPACE: pre">	</SPAN>print.apply(window, arguments);
}
Copy after login

The above article provides an in-depth understanding of the difference between the apply() and call() methods in JavaScript. This is all the content shared by the editor. I hope it can give you a reference, and I hope you will support Script Home.

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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 implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

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.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

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

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

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

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

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

See all articles