Home Web Front-end JS Tutorial A simple comparative analysis of the use of apply, call and this in JavaScript_javascript skills

A simple comparative analysis of the use of apply, call and this in JavaScript_javascript skills

May 16, 2016 pm 03:27 PM
javascript

1.apply definition

apply: Call the function, replace the this value of the function with the specified object, and replace the parameters of the function with the specified array.
Syntax: apply([thisObj[,argArray]])
thisObj
Optional. The object to use as this object.

argArray
Optional. A set of arguments to be passed to the function.

2.call definition

call: Call a method of an object and replace the current object with another object.
Syntax: call([thisObj[, arg1[, arg2[, [, argN]]]]])
thisObj
Optional. The object to be used as the current object.

arg1, arg2, , argN
Optional. The parameter list that will be passed to the method.

3. The difference between the two

The second parameter of call can be of any type, while the second parameter of apply must be an array or arguments.
There are also differences in definitions.

4. Example analysis

(1) Official example:

function callMe(arg1, arg2){
  var s = "";

  s += "this value: " + this;
  s += "<br />";
  for (i in callMe.arguments) {
    s += "arguments: " + callMe.arguments[i];
    s += "<br />";
  }
  return s;
}

document.write("Original function: <br/>");
document.write(callMe(1, 2));
document.write("<br/>");

document.write("Function called with apply: <br/>");
document.write(callMe.apply(3, [ 4, 5 ]));
document.write(callMe.call(3, 4, 5 ));
// Output: // Original function: // this value: [object Window] // arguments: 1 // arguments: 2 // Function called with apply: // this value: 3 // arguments: 4 // arguments: 5

Copy after login

The first one using apply: Definition: Call a function and replace the this value of the function with the specified object
Call the function callMe and replace this in the callMe function with the specified object 3. At this time, this here changes from the previous [object Window] to 3.
The first one uses call: Definition: Call a method of an object and replace the current object with another object.
Call the method of the object callMe and replace the object in callMe with another object 3.
From the analysis of these results, it can be seen that both of them use the object in the specified object or the specified value to change this in the object.
It can also be said that the object (this) in a function "hijacks" the object (this) in another function to be executed.
In fact, this raises a question: What exactly is this? Why is it so important to go through so much trouble to change its direction again and again?

(2) Example:

function zqz(a,b){
  return alert(a+b);
}
function zqz_1(a,b){
  zqz.apply(zqz_1,[a,b])
}
zqz_1(1,2)  //->3 

Copy after login

Analysis: According to the definition: call a function and replace the this value of the function with the specified object,
Here the function zqz is called and the this value of the zqz function is replaced with the specified object zqz_1.

Please note that the function name in js is actually an object, because the function name is a reference to the Function object!

function add(a, b)
{
 alert(a + b);
}
function sub(a, b)
{
 alert(a - b);
}
add.call(sub, 3, 1); // 4

Copy after login

Analysis: According to the definition: Call a method of an object and replace the current object with another object.
Here is the method of calling the object add and replacing the current object sub with the add object;

Another example:

function zqz(a,b){
  this.name=a;
  this.age=b;
  alert(this.name+" "+this.age);
}
function zqz_1(a,b){
  zqz.apply(this,[a,b])   //我们亦可以这么写  zqz.apply(this,arguments) 
}
zqz_1("Nic",12)  //Nic 12

Copy after login

Analysis: According to the definition: call a function and replace the this value of the function with the specified object,
Here, the function zqz is called, using the specified object this to replace the this of the function zqz.

Another example:

<input type="text" id="myText"  value="input text">
function Obj(){
  this.value="对象!";
}
var value="global 变量";
function Fun1(){
  alert(this.value);
}
Fun1();  //global 变量
Fun1.call(window); //global 变量
Fun1.call(document.getElementById('myText')); //input text
Fun1.call(new Obj());  //对象!
Fun1(); //global 变量
Copy after login

Analysis: Definition: Call a method of an object to replace the current object with another object.

Call the method of the Fun1 object to replace the current object in Fun1 with the window object.
Call the method of the Fun1 object and replace the current object in Fun1 with the object in input.
Call the method of the Fun1 object and replace the object in the current Fun1 with the object in the new obj.

Let’s take a look at a question raised by a netizen:

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 the thisObj parameter is not provided, the Global object is used as thisObj.

Then I took it upon myself to write a case, but what I wrote was different from what I imagined; the code is as follows

 function parent()
 {
 alert(this.name);
 }
 function child()
 {
 var name = '张三';
 };
 
 parent.call(child); 
Copy after login

What he outputs is child. Why not Zhang San? According to the above sentence, the parent context has become child

And there is a name value in child. The output should be Zhang San. Please explain

 
 function parent()
 {
 alert(this.name);
 }
 function child()
 {
 this.name = '张三';
 };
 var p1 = new child();
 
 parent.call(p1); 
Copy after login

This can output Zhang San Why?

Let’s see what’s going on

The use of call and apply is that they can be called using variables as function names. For example, the callback function of a function. The specific usage is: executed function.call(a,b,c...), where a is the object that this needs to be specified in the executed function, which can be null, and other parameters are used as parameters of the executed function. The usage of apply is similar, except that the second parameter is an array.

Example:

function doPost(url,param,callback){
  //这里处理post请求
  var str = xhr.responseText;
  callback.apply(this,[str]);//相当于调用了callback(str);并把callback中的this设定为doPost对象
}
Copy after login

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

Video Face Swap

Video Face Swap

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

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

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.

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

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles