Application of call () and apply () in JavaScript

Source: Internet
Author: User

The real purpose of apply () and call () is to expand the scope in which the function is to run

Three-point description:

1 . Each function contains two non-inherited methods: Apply () and call ().

2 . They are used in the same way, and are called functions in a specific scope.

3, the receiving parameters are different, apply () receives two parameters, one is the function run scope (this), and the other is a parameter array.
The first parameter of the call () method is the same as the Apply () method, but the arguments passed to the function must be enumerated.

Usage examples:

First Instance:

        functionprint (A, B, C, D) {alert (a+ B + C +d); }        functionexample (A, B, C, d) {//using the call method to borrow print, parameter explicit break-through transferPrint.call ( This, A, B, C, D); //use the Apply method to borrow print, the parameter is passed as an array,            //here directly with the JavaScript method within the arguments array itselfPrint.apply ( This, arguments); //or encapsulate an array ofPrint.apply ( This, [A, B, C, d]); }        //The "backlight script" is shown belowExample ("Back", "light", "foot", "Ben");
View Code

A second example:

        function Animal (name)        {            this. Name = name;               This function () {                alert (this. Name);            }        }         function Cat (name)        {            Animal.call (this, name);        }                 var New Cat ("Black cat");        Cat.showname ();    
        functionAnimal (name) { This. Name =name;  This. ShowName =function() {alert ( This. Name); }        }        functionCat (name) {Animal.call ( This, name); } Cat.prototype=NewAnimal (); varCat =NewCat ("Black cat");        Cat.showname (); Alert (CatinstanceofAnimal);

Application of call () and apply () in JavaScript

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.