javascriptprototypeobject-model

JavaScript: What are .extend and .prototype used for?


I am relatively new to JavaScript and keep seeing .extend and .prototype in third party libraries I am using. I thought it had to do with the Prototype javascript library, but I am beginning to think that is not the case. What are these used for?


Solution

  • Javascript's inheritance is prototype based, so you extend the prototypes of objects such as Date, Math, and even your own custom ones.

    Date.prototype.lol = function() {
     alert('hi');
    };
    
    ( new Date ).lol() // alert message
    

    In the snippet above, I define a method for all Date objects ( already existing ones and all new ones ).

    extend is usually a high level function that copies the prototype of a new subclass that you want to extend from the base class.

    So you can do something like:

    extend( Fighter, Human )
    

    And the Fighter constructor/object will inherit the prototype of Human, so if you define methods such as live and die on Human then Fighter will also inherit those.

    Updated Clarification:

    "high level function" meaning .extend isn't built-in but often provided by a library such as jQuery or Prototype.