The Apply method of JavaScript function and the call method

Source: Internet
Author: User

First, the function is a pointer to a function object, and the name of the functions is a pointers to functions. Then in the function body, there will be a scope, that is the this keyword.

The This keyword refers to the scope of the function run, for example:

<script type= "Text/javascript" > Function Funca () {alert (this);        Alert ("Function A"); }</script>

The function Funca in the above code is defined in the global environment, then this is the Window object in the function body.

The following is the description of call and apply. Taking the call function as an example, the first parameter of call is to change the scope of the function, and the parameters that follow are the parameters required to pass in the function, which must always be with the parameters of the original function, for example:

We defined the FUNCB function, called the call function of the Funca, and this time we changed the direction of this in Funca, which pointed to the window, and now points to the first parameter, the Testo object. and call, because the Funca function has two parameters, so if you want to Funca pass parameters, you must one by one to indicate the parameters, that is, two parameters A and B after, or you can wear only the first parameter

namely: Funca.call (TestO), or only a, namely: Funca.call (Testo,a);

The only difference between apply and call is that the second argument of apply can be in the form of an array, without having to one by one indicate the parameter, funca.apply (Testo,[a,b])

Introduction to the basic use of call and apply, it is said that his brother really useful, expand the function to run the scope.

<script type= "Text/javascript" >        window.color =   "Transparent";        var testobj = { color:  "red" " };                 FUNCTION&NBSP;TESTFUC ()  {             Console.info (This.color);        }         $ (function  ()  {             Testfuc ();  //pops up "Transparent"             testfuc (this);  //pop-up "undefined"             testfuc.call ( this.parent)  //pop-up "Transparent"              Testfuc.call (window);  //popup "Transparent"              testfuc.call (TESTOBJ);  //pop-up "red"          });</script>

The above code demonstrates the role of call. The first function call, this points to window, so pops the window's Color property.

The second function may have some friends who think that it will also pop up transparent, but first make sure our function runs in $ (function () {}); In this jquery function, knowing that jquery's friends are very clear in $ (function () {}); In the scope of this is the document, and then we call TestFunc, to pop up the color of the document, of course undefined. (The "Transparent ..." pops up when I test)

The third function points TestFunc's this to the parent window of document, and the color of the popup window is certainly not a problem.

The fourth function is more straightforward, and the window is passed in.

The fifth function, which points the testfunc this to testobj, pops up red.

In this case, the usage should be understood, but specifically how to understand how to use or to see their own routines.

I understand that this usage can be seen as a generic method in C # or Java. Like the definition of a C # method

The code is as follows:

public void test<t> (t A, T b) {}

This allows us to extend the method to achieve a common purpose.

The above are my own views and views, what is wrong and please point out to learn together.

Let me give you an example to understand:

The jquery call method is in contact with the Apply method:

call method : &NBSP;
Syntax: Call ([thisobj[,arg1[, arg2[,   [,. ArgN ]] []]  
Definition: The method is called to replace the current object with another object.  
Description:  
The call  method can be used to invoke a method in place of another object. The call  method can change the object context of a function from the initial context to a new object specified by  thisObj . &NBSP
If the  thisObj  parameter is not provided, then the  Global  object is used as  thisobj.  

Apply method:  
Syntax: Apply ([Thisobj[,argarray]])  
Definition: Replaces the current object with another object to apply the method.  
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 a  thisobj, and cannot be passed any parameters.  

<script language= "JavaScript" ><!--       /** Define a animal class */       function animal () {            this.name =  "Animal";            this.showname = function () {                alert (this.name);            }        }       /** defines a cat class */       function cat () {            this.name =  "Cat";       }              /** create two Class objects */      var animal  = new animal ();        var cat = new cat ();              //using the call or Apply method, the ShowName () method that originally belonged to the animal object is given to the current object, Cat.          //the caller of the ShowName () method is animal, but the call function turns the caller of the method into cat, function or ShowName () function,     //only the caller has changed, so the pointer to this within the ShowName () function becomes cat, not animal      animal.showname.call (Cat, ",");   //input result is "cat"      // Animal.showName.apply (cat,[])  //input result "cat"    </script>

The above code, either with the Animal.showName.call or the Animal.showName.apply method, results in a string that outputs a "Cat". indicates that the caller of the ShowName method was replaced with a cat object instead of the animal that originally defined it. This is the magic of call and apply Method!

The Apply method of JavaScript function and the call method

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.