The Apply () and call () methods in JavaScript use notes

Source: Internet
Author: User
Tags inheritance

The first argument to call () and apply () is the object of the function to invoke, which is the value of this keyword in the function body.

The remaining arguments for call () are the values passed to the function to be invoked.

The structure is as follows: Call ([thisobj[,arg1[, arg2[, [,. argn]]]]


The first parameter of the call () method is the same as the Apply () method, but the arguments passed to the function must be enumerated

The code is as follows Copy Code

<script type= "Text/javascript" >
function Box (name, age) {
This.name= name;
This.age = age;
this.family = [' elder brother ', ' sister ']; Reference type, which is not shared inside the construct
}
Box.prototype.family = ' family '; Doesn't work
function Desk (name, age) {
Box.call (this, name,age);//object impersonate, only inherit the information in the structure
}
var desk = new Desk (' Caibaojian ', 27);
alert (desk.family);
Desk.family.push (' younger brother ');
alert (desk.family);
var desk2 = new Desk (' Jack ', 22);
alert (desk2.family);
</script>

Example 1:

The code is as follows Copy Code

Window.firstname = "Diz";
Window.lastname = "song";
var myObject = {firstName: "My", LastName: "Object"};
function Helloname () {
Console.log ("Hello" + This.firstname + "" + This.lastname, "Glad to meet you!");
}
Helloname.call (window); Huo. Call (this);
Helloname.call (MyObject);

The results of the operation are:
Hello Diz song glad to meet you!
Hello my Object glad to meet you!

Example 2:

The code is as follows Copy Code


function sum (NUM1, num2) {
return NUM1 + num2;
}
Console.log (Sum.call (window, 10, 10)); 20
Console.log (Sum.apply (window,[10,20)); 30

Of course it may be used in other ways, but I'm not quite sure how it works. The real explanation is that the call method invokes one method of an object and replaces the current object with another object. Call ([thisobj[,arg1[, arg2[, [,. argn]]]] There is an example on the web that explains this very well:

The code is as follows Copy Code

<script type= "Text/javascript" >
function Obj () {this.value= Object! ";}
var value= "global variable";
function Fun1 () {alert (this.value);}

Window. Fun1 (); Global variables
Fun1.call (window); Global variables
Fun1.call (document.getElementById (' MyText ')); Input text
Fun1.call (New OBJ ()); Object!
</script>
<input type= "text" id= "MyText" value= "input text" >

The use of apply is similar to call, except that the parameters are changed to an array. And it can also use the arguments declaration to invoke:

The code is as follows Copy Code

<script type= "Text/javascript" >
function Box (name, age) {
This.name= name;
This.age = age;
This.run = function () {
Return this.name+ "are" +this.age + "year old";
}
};
function Saybox () {
Box.apply (this,arguments);
}
var saybox = new Saybox (' caibaojian.com ', 2);
Alert (Saybox.run ()); Caibaojian.com is 2 old
</script>

This is only true if the order of the parameters in the superclass is exactly the same as the order of the parameters in the subclass.

If you don't understand, read the following the code listed by the original author can be interpreted as follows: the call () method is the method to invoke the object (function) in front of the called () method using the attributes or parameters in the thisobj.

The popular thing to say is

The call () method can be used to invoke a method instead of another object. The call method can change the object context of a function from the initial context to the new object specified by Thisobj.

The code is as follows Copy Code

[CC lang= ' JavaScript ']
function Add (a,b)
{
alert (A+B);
}
function sub (a,b)
{
alert (a-b);
}

Add.call (sub,3,1);
[/CC]

Add instead of sub to accept the 3 and 1 parameters, which are equivalent to add (3,1)

More complicated code is easier to understand, so let's take a look at how this thing works.

The code is as follows Copy Code

[CC lang= ' JavaScript ']
function Class1 ()
{
THIS.name = "Class1″;

This.shownam = function ()
{
alert (this.name);
}
}

function Class2 ()
{
THIS.name = "Class2″;
}

var C1 = new Class1 ();
var C2 = new Class2 ();

C1.showNam.call (C2);
[/CC]

Call means to put the C1 method on the C2, the original C2 is not the Shownam () method, now is the C1 Shownam () method to carry out the C2, so this.name should be class2, the implementation of the result is: alert ("Class2 ″);

I feel this sentence can be so understood, C1 executes the ShowName method, but in which this is replaced by the object C2

Call () can also implement inheritance, continue to look at the original pasted code,

The code is as follows Copy Code

[CC lang= ' JavaScript ']
function Class1 ()
{
This.showtxt = function (TXT)
{
alert (TXT);
}
}

function Class2 ()
{
Class1.call (this);
}

var C2 = new Class2 ();

C2.showtxt ("CC");
[/CC]

Class2 called the Class1 Call () method, where this is already c2. Then it is equivalent to C1.showText.call (C2, ' cc '), as explained above, without repetition.

Call () can also achieve multiple inheritance, uh. Since the original author did not complete the code here, I will fix it and make it easier for me to understand

The code is as follows Copy Code

[CC lang= ' JavaScript ']
function Class10 ()
{
This.showsub = function (a,b)
{
alert (a-b);
}
}

function Class11 ()
{
This.showadd = function (a,b)
{
alert (A+B);
}
}

function Class2 ()
{
Class10.call (this);
Class11.call (this);
}

var C2 = new Class2 ();

C2.showadd (1,2);

C2.showsub (2,1);
[/CC]

The two call () method implements multiple inheritance. Oh.

The Apply () method is exactly the same as the call () method, except that the arguments to be invoked after the Apply () method are given in the form of an array: [0,1]. Oh.

Summarize

1, each function contains two methods that are not inherited: Apply () and call ().
2, which is the same for their purpose, is to call a function in a specific scope.
3, receive parameters differ, apply () receives two parameters, one is the scope of the function run (this), and the other is a parameter array.

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.