Summary of the call () method and the Apply () method usage

Source: Internet
Author: User
Tags getmessage

1. Each function contains two non-inherited methods: The call () method and the Apply () method. 2. The same point: the two methods work the same way.

is to call a function in a specific scope, equal to the value of the this object in the body of the function to expand the scope on which the function is run.

Generally, this always points to the object that invokes a method, but when you use the call () and the Apply () method, the point of this is changed.

The call () method uses an example:

    //例1
<script>Window.color='Red'; Document.color='Yellow'; varS1 = {color:'Blue' }; function ChangeColor () {Console.log ( This. color);         } changecolor.call (); //Red (default pass parameter)Changecolor.call (window);//RedChangecolor.call (document);//YellowChangecolor.call ( This);//RedChangecolor.call (S1);//Blue</script>//Example 2    varPet ={words:'...', speak:function (say) {Console.log (say+"'+ This. Words)} } pet.speak ('Speak');//results: Speak ...    varDog ={words:'Wang'    }    //change the direction of this to dogPet.speak.call (Dog,'Speak');//results: Speakwang

The Apply () method uses the example:

    //例1
<script>Window.number=' One'; Document.number=' Both'; varS1 = {Number:'three' }; function ChangeColor () {Console.log ( This. number);         } changecolor.apply (); //One (default parameter)changecolor.apply (window);// OneChangecolor.apply (document);// BothChangecolor.apply ( This);// OneChangecolor.apply (S1);//three</script>//Example 2function Pet (words) { This. Words =words;  This. Speak =function () {Console.log ( This. Words)} } function Dog (words) {//Pet.call (this, words);//Result: WangPet.apply ( This, arguments);//Result: Wang    }    varDog =NewDog ('Wang'); Dog.speak ();
3. Different points: Receive parameters in different ways.
    • The Apply () method receives two parameters, one is the scope of the function run (this), and the other is the parameter array.

Syntax: apply([thisObj [,argArray] ]); to invoke one of the object's methods, 2 replaces the current object with another object.

Description: If Argarray is not a valid array or is not a arguments object, it will result in a
TypeError, if none of the Argarray and Thisobj parameters are provided, then the global object will be used as the thisobj.

    • Call () method The first argument is the same as the Apply () method, but the arguments passed to the function must be enumerated.

Syntax: call([thisObject[,arg1 [,arg2 [,...,argn]]]]); a method of applying an object that replaces the current object with another object.

Description: The call method can be used to invoke a method in place of another object, which can change the object context of a function from the initial context to the new object specified by Thisobj, and if the Thisobj parameter is not provided, the global object is used for thisobj.

Using Example 1:

function Add (c,d) {        returnthis this. B + C + D;    }     var s = {A:1, B:2};    Console.log (Add.call (S,3,4//  1+2+3+4 = ten    console.log ( Add.apply (s,[5,6//

Using Example 2:

<script>Window.firstname="Cynthia"; Window.lastname="_xie"; varMyObject = {firstName:'my', LastName:'Object'}; function GetName () {Console.log ( This. FirstName + This. LastName); } function GetMessage (sex,age) {Console.log ( This. FirstName + This. LastName +"Gender:"+ Sex +"Age :"+Age ); } getname.call (window); //Cynthia_xieGetname.call (MyObject);//MyObjectgetname.apply (window);//Cynthia_xieGetname.apply (MyObject);//MyObjectgetmessage.call (window,"female", +);//cynthia_xie Sex: female age:21Getmessage.apply (window,["female", +]);//cynthia_xie Sex: female age:21Getmessage.call (MyObject,"Unknown", A);//myObject Sex: Unknown age:22Getmessage.apply (myobject,["Unknown", A]);//myObject Sex: Unknown age:22</script>
4, under what circumstances with apply, under what circumstances with call

In the case of an object parameter, if the argument is in the form of an array, such as the parameter arguments is passed in the apply example, the parameter is an array type, and the list of parameters is consistent when the person is called ( That is, the first two bits of the parameter list of the person and student are consistent) can be applied, if my person's parameter list is such (Age,name), and Student's argument list is (Name,age,grade), This can be done with call, that is, directly specify the position of the corresponding value of the parameter list (Person.call (This,age,name,grade));

<script type="Text/javascript">/*Define a human*/function Person (name,age) { This. name=name;  This. age=Age ; }      /*define a student class*/functionstudent (Name,age,grade) {person.apply ( This, arguments);        Person.call (This,name,age);  This. grade=grade; }      //Create a Student class    varStudent=NewStudent ("Zhangsan", +,"First Grade"); //TestAlert"Name:"+student.name+"\ n"+"Age :"+student.age+"\ n"+"Grade:"+Student.grade); //You can see the test results Name:zhangsan age:21 Grade: First grade//I did not assign a value to the name and age attribute in the student class, why is there the value of these two properties, this is the magic of apply. </script>

4. Some other clever uses of apply

The attentive person may have noticed that when I invoke the Apply method, the first argument is the object (this), the second argument is an array collection, and when you call person, he doesn't need an array, but why does he give me an array I can still parse the array into one parameter, This is a clever use of apply, you can convert an array by default to a parameter list ([PARAM1,PARAM2,PARAM3] to PARAM1,PARAM2,PARAM3) This if let us use the program to implement the array of each item, To load a list of parameters, it may take a while, with this feature of apply, the following efficient methods are available:

A) Math.max can be implemented to get the largest item in the array

Because the Math.max parameter does not support Math.max ([PARAM1,PARAM2]), which is the array

But it supports Math.max (param1,param2,param3 ...), so you can solve the Var max=math.max.apply (Null,array) According to the characteristics of the just apply. This makes it easy to get the largest item in an array (apply will change a number assembly to a parameter by passing it to a method)

This block in the call when the first parameter gave a null, this is because there is no object to call this method, I just need to use this method to help me to calculate the return of the results on the line. So it passed directly a null past

b) Math.min can be implemented to get the smallest item in the array

Likewise and Max is a thought var min=math.min.apply (Null,array);

c) Array.prototype.push can implement two array merging

The same push method does not provide an array of push, but it provides push (Param1,param,... paramn) So it is also possible to replace this array with apply, namely:

vararr1=New Array ("1","2","3 " );    VARARR2=new Array ("4","5", " 6 " );    Array.prototype.push.apply (ARR1,ARR2);  

It is also possible to understand that arr1 invokes the push method, which is a set of parameters that can be assembled into a parameter list by using apply.

Under what circumstances, you can use a special usage like math.min and so on:

In general, the target function requires only n argument lists, not the form of an array ([param1[,param2[,... [, Paramn]]] ), you can solve this problem skillfully by apply way!

Summary of the call () method and the Apply () method usage

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.