Summary of call and apply usage in js

Source: Internet
Author: User

I went to the interview the day before yesterday. gg asked some js knowledge, including a call and apply usage question. Although I used the call method 365 days ago, I still couldn't answer it, summary today

Call and apply. They are used to bind a function to another object and run the function.

The format and parameter definitions of the two are as follows:

Call (thisArg [, arg1, arg2 ,... ]); // Parameter list, arg1, arg2 ,...
Apply (thisArg [, argArray]); // parameter array, argArray

The this pointer inside the above two functions will be assigned to thisArg, which can be used to run the function as a method of another object.

I. Simple call usage

First, let's take a look at a simple example (call ):
Copy codeThe Code is as follows:
<! Doctype html>

<Html>
<Head>
<Title> call-apply </title>
</Head>

<Body>
<Input type = "text" id = "idTxt" value = "input text">

<Script type = "text/javascript">
Var value = "global var ";

Function mFunc ()
{
This. value = "member var ";
}

Function gFunc ()
{
Alert (this. value );
}

Window. gFunc (); // show gFunc, global var
GFunc. call (window); // show gFunc, global var
GFunc. call (new mFunc (); // show mFunc, member var
GFunc. call (document. getElementById ('idtxt '); // show element, input text
</Script>

<Script language = "javascript">
Var func = new function ()
{
This. a = "func ";
}

Var func2 = function (x)
{
Var a = "func2 ";
Alert (this. );
Alert (x );
}

Func2.call (func, "func2"); // show func and func2
</Script>
</Body>
</Html>

The running result is as follows:

Global var
Global var
Member var
Input text
Func
Func2

Test environment: Google Chrome 10.0.648.45

Finally, the analysis results

1. The Global Object window calls the gFunc function,This points to the window object., So this. value isGlobal var

2. The function gFunc calls the call method,This points to the first window object by default., So this. value isGlobal var

3. The function gFunc calls the call method,This points to the first parameter new mFunc () by default, that is, the mFunc object.Therefore, this. value is a member variable of mFunc.Member var

4. The function gFunc calls the call method,This points to the first input text control by default, that is, the control with id = 'idtxt '.Therefore, this. value is the value of the input control.Input text

5. The function func2 calls the call method,This points to the first func function object by default.So this. value is this. a, that isFunc

6. The function func2 calls the call method,The second parameter belongs to the func2 parameter of the function object.Therefore, alert (x) is the second parameter.Func2


Ii. call inheritance usage and Improvement

Js uses call to simulate inheritance

Test code:
Copy codeThe Code is as follows:
<! Doctype html>

<Html>
<Head>
<Title> call-apply for inherit </title>
</Head>

<Body>
<Script type = "text/javascript">
Function baseA () // base Class
{
This. member = "baseA member ";
This. showSelfA = function ()
{
Window. alert (this. member );
}
}

Function baseB () // base Class B
{
This. member = "baseB member ";
This. showSelfB = function ()
{
Window. alert (this. member );
}
}

Function extendAB () // Inherit Class from A and B
{
BaseA. call (this); // call for
BaseB. call (this); // call for B
}

Window. onload = function ()
{
Var extend = new extendAB ();
Extend. showSelfA (); // show
Extend. showSelfB (); // show B
}
</Script>
</Body>
</Html>

The running result is as follows:

BaseB member
BaseB member

Test environment: Google Chrome 10.0.648.45

Result Analysis:

Expected results should be outputBaseA member and baseB memberBut the actual output isBaseB member and baseB member

(It has been tested in IE9, 8, 6, Maxthon, Chrome, FF, Opera, Safari, 360, and other browsers. The result is the latter: baseB member)

At this point, the machine will not be wrong, which requires in-depth analysis.

We may easily think of this as the cause. this points to the baseB object twice, but is it true?

In order to explore the essence, we use the debugging tool of chrome browser to debug the breakpoint. The results show that:


WhenExtend. showSelfA ();This points to extendAB (This is not what we have speculated to direct to the baseB object twice.)

The real reason is that the member variable member of the extendAB object isBaseB. call (this );During instantiation, It is overwritten by the baseB member, that is, the extendAB member is assigned the value from baseA member to baseB member.

Of course, we can also slightly modify the above baseA code to verify the correctness of our debugging analysis:
Copy codeThe Code is as follows:
Function baseA () // base Class
{
This. memberA = "baseA member"; // change member to memberA to distinguish the member in baseB.
This. showSelfA = function ()
{
Window. alert (this. memberA); // display memberA
}
}

Run chrome and other browsers again. The result is as follows:

BaseA member
BaseB member

The results are the same as we expected, and the chrome debugging information also verifies our correctness:

Prototype)

The above simulation inheritance method is not the best for careful analysis.

Because every time a Member method is defined in a function (class), the instance has a copy, so you can use the prototype to improve

An example of improvement is as follows:
Copy codeThe Code is as follows:
<! Doctype html>

<Html>
<Head>
<Title> call-apply for prototype </title>
</Head>

<Body>
<Script type = "text/javascript">
Var Class = {
Create: function () // create Function
{
Return function ()
{
This. initialize. apply (this, arguments );
}
}
};

Var Person = Class. create (); // Create Class Person
Person. prototype = {// prototype initialize
Initialize: function (obj1, obj2)
{
This. obj1 = obj1;
This. obj2 = obj2;
},
ShowSelf: function ()
{
Alert ("obj:" + this. obj1 + "and" + this. obj2 );
}
}

// Instance Class
Var person = new Person ("man", "women"); // two params
Person. showSelf (); // show person
</Script>
</Body>
</Html>

The running result is as follows:
Obj: man and women

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.