search
HomeWeb Front-endJS TutorialA simple comparative analysis of the use of apply, call and this in JavaScript_javascript skills

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

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 

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

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

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

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

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

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对象
}

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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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.