JS and then call and apply

Source: Internet
Author: User

As we continue to study the Ajax framework, we are more exposed to call and apply.
So we will discuss call and apply again,
1) undoubtedly, the simplest explanation of call is to display the hidden first parameter. Generally, when a function is called, an additional hidden parameter is the object to which the function belongs (if it is not specific to it, it is global (such as window) object), you can use this keyword to access the function.
Call (thisarg [, arg1, arg2…] ]).
The call (apply) method can change the object context (function context) of a function from the initial context to the new object specified by thisobj, which is the biggest advantage of call (apply. Speaking of this, we may mention what the so-called function context is. Let's take a look at functioncontextdemo below:

VaR Changed = { Item: "banana ", Act: "Eating" };
VaR Original = {
                Item: "Chair ",
                Act: "Sitting In ",
              Ask: Function (){
                            Return "Who's Been "+ This. Act +" My "+ This. item;
                }
};
Alert ("original : " + Original. Ask ());
Alert ("not So Simple, that Have Been Changed To: " + Original. Ask. Call (changed ));

Parse the above Code:
At first, two objects changed and original exist. Changed is an array with the item and act attributes respectively, while original has the same item and act attributes as changed, there is also a ask function (asking who is sitting in the chair), so when you call original. the expected result is as follows: Who's been sitting in my chair. let's take a closer look, when we call original. ask. what do you think will happen during call (changed? Here, call is used to give the original method (function) ask to the changed object for execution. The changed method does not have the ask method (function). After this binding, the function context is the changed object. Therefore, this called in the method (function) Ask should be a changed object. Therefore, original can be inferred. ask. the call (changed) result should be: Who's been eating my banana.

The functioncontextdemo example shows that if we need to replace the function context in the programming process, call is a good choice.
You can try to modify the functioncontextdemo example as follows to see what the result is:
VaR changed = {item: "banana", act: "eating "};
VaR original = {item: "Chair", act: "sitting in "};
Function ask (){
  Return "who's been" + this. Act + "my" + this. item;
}
Alert ("Original:" + ask. Call (original ));
Alert ("changed:" + ask. Call (changed ));

2) How does JavaScript use call to simulate inheritance in object-oriented systems and implement multi-inheritance?

// Multi-Inheritance
Function Base1 () {
        This. Member = " Base#member ";
        This. showself = Function () {
                Window. Alert (this. member );
        }
}
Function Base2 () {
        This. Person = " Base2_member ";
  This. Act = " Is Dancing Happily ";
        This. showaction = Function () {
                Window. Alert (this. Person + This. Act );
        }
}
Function Extend () {
        Base1.call (this );
        Base2.call (this );
}
Window. onload = function (){
      VaR Demo = New Extend ();
      Demo. showself ();
      Demo. showaction ();
}

But take a closer look. This inheritance is problematic. Defining the member method in the class function body will result in a copy of each instance, occupying the memory again.
The most elegant and concise method should be based on prototype inheritance.
3) Next, let's take a look at how the Javascript prototype uses apply to create a schema for defining classes:
VaR class = {
 Create: function (){
   Return function (){
     This. Initialize. Apply (this, arguments );
   }
 }
};
Resolution:
From the code, this object only contains one method: Create, which returns a function, that is, a class. But this is also a class constructor, where initialize is called, and this method is the initialization function defined during class creation, so that the class Creation Mode in prototype can be implemented. the purpose is to define such a class creation mode so that the class's initialization function name must be initialize (), and this. initialize. apply (this, arguments); (confusing) ensures that initialize will be called after the class instance is created, which facilitates management and reflects the idea of object-oriented.

Note: This is actually the same object, that is, the class itself calls its own constructor to create a class object! Because the second parameter of the apply method must be an array, the parameter passed to this function is also passed to the initialize method of the class. If it is directly written as this. initialize (arguments); All parameters are passed to the initialize constructor as an array.

VaR Vehicle = Class. Create ();
Vehicle. Prototype = {
        Initialize: function (type ){
                This. type = type;
        }
        Showself: function (){
                Alert ("This Vehicle Is "+ This. type );
        }
}

VaRMoto = newVehicle ("Moto ");
Moto. showself ();

4) apply (JavaScript framework prototype event binding ):
Function. Prototype. Bind = function (){
 VaR _ method = this;
 VaR ARGs = $ A (arguments );
 VaR object = args. Shift ();
 Return function (){
   // Call the apply method of the function to execute the function, where the object is the target object, and The args is the list of parameters in the bind method (an array consisting of parameters other than the first parameter)
   Return _ method. Apply (object, argS. Concat ($ A (arguments); // In fact, $ A (arguments) here must be an empty array
 }
}
Code parsing:
This BIND is used to bind a function to a specific function for execution,
A) VaR _ method = This; first, the function context is assigned to a local variable to make it in closure (this is a javascript feature and can be interpreted as a "closure ") can be accessed, so you can easily obtain it below. It is actually the caller of the BIND method and a function object.
B) var ARGs = $ A (arguments); here, because arguments is an object of the class array, the parameters passed into the bind method are converted to array through $ A (arguments.
C) var object = args. shift (); get the target object by intercepting the first parameter of argS. At this time, argS is an array composed of parameters other than the first parameter)
D) This is the most critical step. Return a new function object (a function without any parameters) and use apply to call _ method (the caller of the BIND method) bind to the target object and give the ARGs array composed of all parameters except the target object. concat ($ A (arguments), the final target object (target object) can execute _ method.
The advantage of binding a function with so much effort is that you do not need to worry about the extra concerns caused by function context confusion.

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.