


Clarify the differences and relationships between apply() and call()_javascript skills
If you encounter this feeling in the process of learning JavaScript, a free and ever-changing language, then from now on, please put aside your "prejudice", because this is definitely a new world for you, let JavaScript Slowly melt the previously solidified programming consciousness and inject new vitality!
Okay, let’s get back to the subject. Let’s first understand the dynamic change runtime context feature of JavaScrtipt. This feature is mainly reflected in the use of the apply and call methods.
To distinguish apply, call is just one sentence,
foo .call(this, arg1,arg2,arg3) == foo.apply(this, arguments)==this.foo(arg1, arg2, arg3)
call, apply all belong to Function.prototype A method, which is implemented internally by the JavaScript engine. Because it belongs to Function.prototype, each Function object instance, that is, each method has call and apply attributes. Since they are attributes of the method, their use is of course It’s about methods. These two methods are easy to confuse because they have the same function, but they are just used in different ways.
Similar points: The effects of the two methods are exactly the same.
Differences: The methods are passed The parameters are different
So what is the role of the method and what are the parameters passed by the method?
Let’s analyze the foo.call(this, arg1, arg2, arg3) above.
foo is a method , this is the context-related object when the method is executed, arg1, arg2, arg3 are the parameters passed to the foo method. The so-called context-related objects when the method is executed here, if you have the basis of object-oriented programming, it is easy to understand, it is in the class instance this in the transformed object.
In JavaScript, the code always has a context object, and the code processes the 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.中.
To better understand what this is, give an example.
/Create a class A
function A(){
//The following code will be run when the class is instantiated
//The execution context object at this time is this, which is the current instance Object
this.message = "message of a";
this.getMessage = function(){
return this.message;
}
}
//Create a class A Instance object
var a = new A();
//Call the class instance getMessage method to get the message value
alert(a.getMessage());
//Create a class B
function B(){
this.message = "message of b";
this.setMessage = function(msg){
this.message = msg;
}
}
//Create a class B instance object
var a = new B();
Digression: All properties of JavaScript objects are public (public), there is no such thing as private (private) , so you can also directly access the message attribute
alert(a.message);
It can be seen that classes A and B both have a message attribute (a member in object-oriented terms), and A has a getMessage method for getting messages. B has the setMessage method for setting messages. The power of call is shown below.
//Dynamically assign the setMessage method of b to object a. Note that a itself does not have this method!
b.setMessage.call(a, "a's message");
/ /The following will display "a's message"
alert(a.getMessage());
//Dynamically assign a's getMessage method to object b. Note that b itself does not have this method!
This is the power of the dynamic language JavaScript call!
It is simply "made out of nothing". The object's methods can be assigned arbitrarily, but the object itself has never had such a method. Note that it is assignment. In layman's terms, The method is lent to the call of 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 time The context object calls the setMessage method of the b object, and this process has nothing to do with b. The function is equivalent to a.setMessage("a's message");
Because apply and call have the same effect, you can
The function of call and apply is to borrow other people's methods to call, just like calling your own.
Okay, I understand the similarities between call and apply--after they work, let's take a look at their differences. After reading the above I believe you probably know the example.
From b.setMessage.call(a, "a's message") is equivalent to a.setMessage("a's message"), we can see that "a's message" is in call is passed as a parameter in
So how is it expressed in apply? It is not clear in direct explanation. Apply must 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){
// Use the call method to borrow print, and the parameters are explicitly broken up and passed
print.call(this, a, b, c, d);
//Use the apply method to borrow print, and the parameters are passed as an array,
//Here, directly use the arguments array in the JavaScript method
print.apply(this, arguments);
//or encapsulate it into an array
print.apply(this, [a, b, c, d]);
}
//The "backlight script" will be displayed below
example("back", "light", "feet", "this");
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 directly called, so in The context object this in this method is the window object.
Therefore, 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. Apply only has two parameters, and the second parameter is passed as an array. So it can be said to be
call. The difference between the apply method is that starting from the second parameter, the call method parameters will be passed to the borrowed method as parameters in turn. Apply directly puts these parameters into an array and then passes them. The parameter list of the final borrowed method is the same.
Application scenarios:
When the parameters are clear, call can be used, and when the parameters are unclear, apply can be used Give arguments
//Example
print.call (window, "back", "light", "foot", "this");
//The foo parameter may be multiple
function foo(){
print.apply(window, arguments) ;
}

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











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.

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.

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.

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.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.
