Deep understanding of the difference between the Apply () and call () methods in JavaScript _javascript tips

Source: Internet
Author: User
Tags getmessage

If you haven't contacted a dynamic language, it will be a magical and weird feeling to understand JavaScript in a compiled language, because the things that are often impossible in consciousness happen, and even feel unreasonable. If you're learning JavaScript in a free and changing language, this is the way you feel. , then from now on, please put down your "prejudice", because this is absolutely a new continent for you, let Javascrip slowly melt before a set of coagulation programming consciousness, inject new vitality!

Well, to start with, understand the Javascrtipt dynamic transformation Run-time context characteristics, which is mainly embodied in the application, call two methods of use.

Distinguish Apply,call on the word,

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


Call, apply all belong to a Function.prototype method, which is implemented within the JavaScript engine because it belongs to Function.prototype, so each function object instance, each method has a call , the Apply property. Since they are used as a property of a method, their use is, of course, for the method. These two methods are easy to confuse because they work just the same way.

Same point: Two methods produce exactly the same effect

Different points: The parameters passed by the method are different

What is the function of the method, and what are the parameters of the method passed?

We start the analysis on the Foo.call (this, arg1, arg2, Arg3) above.

Foo is a method, this is a context-sensitive object for method execution, Arg1, arg2, ARG3 is a parameter passed to the Foo method. Here is the so-called method execution when context-related objects, if there is an object-oriented programming base, it is well understood that this is in the object after the class is instantiated.

In JavaScript, the code always has a context object that the code handles within the object. The context object is represented by the this variable, which always points to the object where the current code is.

For a better understanding of what this is, give an example.

/Create a Class A
function A () {
//class instantiation will run the following code
//The execution context object at this point is this, which is the current instance object
this.message = "message of A";
This.getmessage = function () {
<span style= "White-space:pre" >	</span>return this.message;
<span style= "White-space:pre" >	</span>}
///Create a Class A instance object
var a = new A ();
Invokes the class instance GetMessage method to obtain the message value
alert (A.getmessage ());
Create a B class
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>}
///Create a class B instance object
var a = new B ();

As you can see, A, Class B has a message attribute (an object-oriented member), a GetMessage method for getting messages, B has a Setmessage method for setting messages, and the power of call is shown below.

Give object a a dynamic assignment of B's Setmessage method, note that a itself is not the way!
B.setmessage.call (A, "a message");
The message "a"
alert (A.getmessage ()) is displayed below.
The GetMessage method of dynamically assigning a to object B, note that B itself is not this way!

This is the power of dynamic language JavaScript call!

is simply "Nothing", the object of the method can be arbitrarily assigned, and the object itself has been no such method, attention is assigned, popular point is that the method is to lend another object to the call to complete the task, the principle is the method execution when the context object changed.

So B.setmessage.call (A, "A's Message"); is equal to using a as the context object to invoke the Setmessage method of B object, which has nothing to do with B, which is equivalent to the A.setmessage ("a Message");

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

Call, apply function is to borrow other people's method to invoke, just like call oneself of the same.

Well, understand the call, apply the same place-– role, and then look at their differences, see the above example, I believe you probably know.

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,

Then in the Apply is how to express it, directly explain not clear, apply to combine the application scene only 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) {
//using the call method to borrow print, the parameters are explicitly beaten and transmitted
Print.call (this, a, B, C, d);
Use the Apply method to borrow print, the parameter is passed as an array,
//Here directly with the JavaScript method itself in the arguments array
print.apply (this, arguments);
or encapsulate an array
of print.apply (this, [A, B, C, d]);
}
The following will show "backlight script"
example ("Back", "light", "foot", "Ben");

In this scenario, in the example method, A, B, C, and D are the parameters passed by the method, using the apply, call to borrow the Print method to invoke,

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

So call, apply methods except for the first parameter, which is the same as the context object at execution time, the other parameters of the call method are then passed to the borrowed method as arguments, and apply is two arguments, and the second argument is an array. So it can be said

Call, apply method The difference is that, starting with the second argument, the calling method parameter is passed to the borrowed method as an argument, and apply directly places the parameters in an array and then passes the argument list of the last borrowed method.


Application Scenario:

Call is available when the parameter is clear, and can be applied to arguments when the parameter is ambiguous

Example
print.call (window, "Back", "light", "foot", "Ben");
The foo parameter may be multiple
function foo () {
<span style= "White-space:pre" >	</span>print.apply (window, arguments);
}

The above in-depth understanding of JavaScript in the application () and call () method is the difference between the small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.