Understanding the differences between the apply () and call () methods in javascript _ javascript skills

Source: Internet
Author: User
The following section provides an in-depth understanding of the differences between the apply () and call () methods in javascript. I think it is quite good. Now I will share it with you and give you a reference. Let's take a look at it together. If you haven't touched any dynamic language, it will be amazing and weird to understand javaScript in the way of thinking in compiled languages, because it is often impossible to realize things happen, and even feel unreasonable. if you encounter this feeling when learning JavaScript, a free and ever-changing language, let go of your "prejudice" from now on ", because this is definitely a new world for you, let the cyber Crip slowly melt the previous set of solidification programming consciousness, inject new life!

Well, let's get down to the point. First, let's understand the context feature of JavaScrtipt's dynamic transformation runtime. This feature is mainly reflected in the application and call methods.

Differentiate apply and call in just one sentence,

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


Call and apply all belong to Function. prototype is implemented internally by the JavaScript engine because it belongs to Function. prototype, so each Function object instance, that is, each method has the call and apply attribute. since they are attributes of methods, their use is of course for methods. these two methods are easy to confuse, because they have the same effect, but they are used in different ways.

Similarities: the two methods have the same effect.

Differences: parameters passed by methods are different.

So what is the role of a method, and what is the parameter passed by the method?

Let's analyze the above foo. call (this, arg1, arg2, arg3.

Foo is a method. this is the context-related object during method execution. arg1, arg2, and arg3 are parameters passed to the foo method. the context-related objects for method execution are well understood if there is an object-oriented programming basis, that is, this in the object after class instantiation.

In JavaScript, the Code always has a context object, and the code processes the object. The context object is reflected by the this variable, which always points to the object where the current code is located.

To better understand what this is, for example.

/Create A class A function A () {// the following code will be run during class instantiation // The execution context object 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 obtain the message value alert (. 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 ();

It can be seen that Class A and Class B all have A message attribute (the Member mentioned in the object orientation), Class A has the getMessage method for obtaining the message, and Class B has the setMessage method for setting the message, the following shows the call power.

// Assign the setMessage method of B to object a dynamically. Note that a itself does not have this method! B. setMessage. call (a, "a's message"); // The following shows "a's message" alert (. getMessage (); // assign the getMessage method of a to object B dynamically. Note that this method is not available for object B!

This is the power of the Dynamic Language JavaScript call!

It is simply an "out of nothing", the object method can be assigned at will, and the object itself has never been using this method. Note that it is assignment. The common point is that, the method is to lend a call to another object to complete the task. In principle, the context object changes during method execution.

So B. setMessage. call (a, "a's message"); It is equivalent to calling the setMessage method of object B when a is used as the execution context object, and there is no relationship with B in this process, the function is equivalent to. setMessage ("a message ");

Because the apply and call functions the same, we can say that

Call, apply is called by someone else's method, just like calling your own.

Well, after understanding the call and apply functions at the same place, let's take a look at their differences. After reading the above examples, I believe you will know about them.

From B. setMessage. call (a, "a Message") is equivalent to. setMessage ("a message") indicates that "a message" is transmitted as a parameter in call,

So how is it expressed in the apply statement? I can't explain it clearly. The apply statement must be used in combination with the Application Scenario. 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 displayed to scatter and pass print. call (this, a, B, c, d); // use the apply method to borrow print. The parameter is passed as an array, // print the arguments array in the JavaScript method. apply (this, arguments); // or encapsulate it as an array print. apply (this, [a, B, c, d]);} // The "backlight script" example ("back", "light", "foot" will be displayed below ", "Ben ");

In this scenario, in the example method, a, B, c, and d are used as the parameters passed by the method. The methods use the apply and call methods to call them by using the print method,

The last sentence calls the example method directly, so the context object in this method is the window object.

Therefore, except for the first parameter, that is, when the context object is the same during execution, other parameters of the call method are passed to the borrowed method as parameters, apply takes two parameters, and the second parameter is passed as an array. so it can be said

The difference between the call and apply methods is that, starting from the second parameter, the call method parameters are passed to the borrowed method as parameters in turn, while the apply method directly places these parameters in an array before passing them, finally, the list of parameters of the borrow method is the same.


Application scenarios:

Call is available when the parameter is clear. If the parameter is not clear, apply to arguments.

// Example print. call (window, "Back", "light", "foot", "Ben"); // foo parameters may be multiple function foo (){Print. apply (window, arguments );}

The difference between the apply () and call () methods in javascript in this article is the whole content shared by Alibaba Cloud. I hope you can give us a reference and support for your feet.

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.