The usage summary of call and apply in JS _javascript skill

Source: Internet
Author: User
Tags inheritance

The day before yesterday to interview, there is a GG asked some JS knowledge, which has a call and apply the use of the topic, although the call method was used 365 days ago, but was still not able to answer, today in-depth summary

Call and apply, and they all function to bind a function to another object to run

Format and parameter definitions for both:

Call (Thisarg [, ARG1,ARG2, ...]); Parameter list, ARG1,ARG2, ...
Apply (Thisarg [, Argarray]); Parameter array, Argarray

The this pointer within the two functions above will be assigned to Thisarg, which enables the function to run as a method of another object

A simple use of call

First, let's look at a simple example (call):

Copy Code code as follows:

<!doctype html>

<title> call-apply </title>

<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.A);
alert (x);
}

Func2.call (func, "Func2"); Show Func and Func2
</script>
</body>


Then, the results of the operation are 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, Global object window Call function Gfunc, thispoints to the Window object, so This.value is global var

2, Function Gfunc call method, thisdefaults to the first parameter window object, so This.value is also global var

3, Function Gfunc call method, thisdefaults to the first parameter new Mfunc (), that is, the Mfunc object, so This.value is the member variable of Mfunc

4, Function Gfunc call method, thisdefaults to the first parameter input text control, that is, id= ' idtxt ' control, so this.value for the input control's value input text

5, Function Func2 call method, thisdefaults to the first parameter Func function object, so This.value is THIS.A, that is func

6. The function Func2 calls the call method, and the second parameter belongs to the FUNC2 parameter of the function object, so alert (x) is the second argument Func2


Second, call inheritance usage and improvement

JS uses call to simulate inheritance

Test code:

Copy Code code as follows:

<!doctype html>

<title> call-apply for Inherit </title>

<body>
<script type= "Text/javascript" >
function Basea ()//base Class A
{
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 A
Baseb.call (this); Call for B
}

Window.onload = function ()
{
var extend = new Extendab ();
Extend.showselfa (); Show A
EXTEND.SHOWSELFB (); Show B
}
</script>
</body>

The results of the operation are as follows:

BASEB Member
BASEB Member

Test environment: Google Chrome 10.0.648.45

Results Analysis:

The expected result should be output Basea member and BASEB member, but the actual output is BASEB member and Baseb member

(Already in IE9, 8, 6,maxthon, Chrome, FF, Opera, Safari, 360 and other browsers tested, the result is the latter: BASEB member)

At this point, the machine is not wrong, which requires us to further analysis

It may be easy to think that this is the cause, this two times all point to the Baseb object, but is it true?

In order to explore the essence, we use the Chrome browser debugging tools, the next breakpoint, debugging, the results found:


When the Extend.showselfa () is invoked, this point points to Extendab ( not all of our guesses point to the Baseb object)

The real reason for this is that the member of the Extendab object is baseb.call (this), and when instantiated, it is overridden by a member of the BASEB, that is, the member of Extendab is represented by Basea Member assignment became BASEB member

Of course, we can also modify the above Basea code slightly to verify the correctness of our debugging analysis:

Copy Code code as follows:

function Basea ()//base Class A
{
This.membera = "Basea Member"; Member changed to Membera to distinguish member in BASEB
This.showselfa = function ()
{
Window.alert (This.membera); Show Membera
}
}

Run Chrome and other browsers again, and the results are as follows:

Basea Member
BASEB Member

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

Inheritance Improvement (prototype)

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

Because every time a member method is defined in a function (class), the instance has a copy, so it can be improved with the help of the prototype prototype

Examples of improvements are as follows:

Copy Code code as follows:

<!doctype html>

<title> call-apply for prototype </title>

<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
The var person = the new Person ("mans", "women"); Two params
Person.showself (); Show person
</script>
</body>


The results of the operation are as follows:
Obj:man and women

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.