A basic understanding of the Apply method in JS

Source: Internet
Author: User

The recent study of Openlayers source code, found that the use of more than the application method, it is also very confused. So the Internet through a wide range of understanding and their own carefully realized, finally is basically understand what it is, here to share.
The styling of the Apply method is such that function.apply (Obj,args) can receive two parameters:
OBJ: This object will replace the This object in the function class
Args: This is an array, which is passed as a parameter.
By online Daniel's explanation is apply: Hijack another object (a) method, inheriting the attribute of a.
To further understand, I made a small example of myself, as follows:

(function () {//    * Defines a method Rockmeber has two properties name, location*/    var rockmeber = function (name, loction) {        this.name = Name;        This.loction = loction;    };    /* Redefine a method Rockteam will call rockmeber*/    var rockteam = function (name, loction, teamname) {         /         * * It can be understood that this is the current rockteam,arguments as an array of parameter lists.         * When you execute the Apply method, this in Rockmeber is Rockteam,         * So Rockteam will also have the name, Location property, and assign the value.         * This (Rockteam) will also be returned. So when we do the output, the Rockteam will have the corresponding attribute value.         * This can also be understood as: Rockmeber attributes are created into the Rockteam object.         *        /rockmeber.apply (this, arguments);                This.teamname = Teamname;    };    $ (' #havetry '). Click (function () {        var rockteam = new Rockteam (' Stone ', ' guitarist ', ' Mayday ');        $ (' #result '). Text (' Name: '   rockteam.name ' '   position: '   rockteam.loction   ' Band: '   rockteam.teamname);})    ;

The comments in the code are more clearly written, not much, and this is my understanding of apply.

Basic understanding of the Apply method in JS

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.