


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

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

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.

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

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.


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

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools

SublimeText3 Chinese version
Chinese version, very easy to use

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.

SublimeText3 English version
Recommended: Win version, supports code prompts!
