JS again on call and apply

Source: Internet
Author: User

Because of the reason for continuing to study the AJAX framework, more contact with call and apply.
So we discuss call and apply again,
1) There is no doubt about call, the simplest explanation is: The hidden first parameter display. Because a function is usually called, there is an extra hidden parameter, which is the object to which the function (functions) belongs (or a global (such as a window) object if not specified), within which you can access the This keyword.
From Call's constructor-call (Thisarg[,arg1,arg2 ...]); Can see
The call method can change the object context of a function from the initial context to the new object specified by Thisobj, which is the greatest advantage of using call. In this regard, we may wish to mention what the so-called function context is. First look at the following functioncontextdemo:

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:
Initially there are 2 objects, changed and original,changed, which are an array of item and Act properties, and original in addition to the item and Act properties that are the same as changed. There is also an Ask function (which asks who is sitting on the chair), so when calling Original.ask (), you can see the expected result: Who's been sitting in my chair. and carefully looking down when we call Original.ask.call (changed), what do you think will happen in the end? In this case, using call to original method (function) Ask to the changed object to execute, originally changed is no Ask method (function), so bound, the function of the object context (functions context) That is the changed object, so in the method (function) Ask in the call of this should be the changed object, you can infer original.ask.call (changed) The result should be: Who's been eating my banana.

The Functioncontextdemo example shows that call is a good choice if we need to replace the object context (function context) of the functions in the programming process.
You can try to change the Functioncontextdemo example as follows and 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 JavaScript uses call to emulate inheritance in object-oriented, and can implement multiple inheritance

Multiple inheritance
function Base1 () {
This.member = "Base1_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, such inheritance is problematic, directly within the class function body to define the member method, will cause each instance has a copy, the memory is repeated.
The most elegant and concise approach should be based on prototype (prototype) inheritance.
3) Next, let's look at how the JavaScript framework prototype uses apply to create a schema that defines a class:
var Class = {
Create:function () {
return function () {
This.initialize.apply (this, arguments);
}
}
};
Analytical:
From the Code view, the object contains only one method: Create, which returns a function, the class. But this is also the constructor of the class, where initialize is called, and this method is the initialization function defined at the time the class is created. In this way, you can implement the class creation pattern in prototype. The purpose is to specify such a class creation pattern, so that the class initializer name must be initialize (), and this.initialize.apply (this, arguments); (confusing) is to ensure that initialize will be called after the instance of the class is created, which is convenient for management and embodies the object-oriented thought.

Note: This is actually the same object, which is equivalent to the class itself calling its own constructor to create a class object! Because the second parameter of the Apply method itself requires an array, the arguments passed to the function are passed to the Initialize method of the class, if written directly as this.initialize (arguments); Then all parameters are passed as an array to the initialize constructor.

var vehicle=class.create ();
vehicle.prototype={
Initialize:function (type) {
This.type=type;
}
Showself:function () {
Alert ("This vehicle is" + this.type);
}
}

var moto=new vehicle ("moto");
Moto.showself ();

4) Apply (the JavaScript framework prototype event bindings):
Function.prototype.bind = function () {
var __method = this;
var args = $A (arguments);
var object = Args.shift ();
return function () {
Call the function's Apply method execution function, where object is the target object, and args is the parameter list in the Bind method (except for the array of parameters other than the first argument)
Return __method.apply (object, Args.concat ($A (arguments)));//In fact, a $ A (arguments) here must be an empty array
}
}
Code parsing:
The bind purpose is to bind a function to a specific function to execute,
a) var __method = this; The function context is first re-assigned to a local variable so that it can be accessed in the closure (which is a JavaScript feature, which can be interpreted as "closed"), so that it can be easily obtained at the bottom. It is essentially the caller of the Bind method and is a function object.
b) var args = $A (arguments); here because arguments is an object of a class array, the arguments passed into the bind method are converted to an array through $ A (arguments).
c) var object = Args.shift (); Gets the target object by intercepting the first parameter of args, at which point args is an array of parameters other than the first argument (array)
D) This is the most critical step in returning a new function object (a function without any arguments), where the __method (the caller of the Bind method) is bound to the target object by apply, and the target object is given in addition to Array Args.concat ($A (arguments)) of all parameters except that the target object is executed __method.
The advantage of being so laborious to bind a function is that you do not have to take into account the additional concerns of the confusion of the function context.

JS again on call and apply (turn)

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.