JavaScript: What are .extend and .prototype used for?
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.
.extend()
is added by many third-party libraries to make it easy to create objects from other objects. See http://api.jquery.com/jQuery.extend/ or http://www.prototypejs.org/api/object/extend for some examples.
.prototype
refers to the "template" (if you want to call it that) of an object, so by adding methods to an object's prototype (you see this a lot in libraries to add to String, Date, Math, or even Function) those methods are added to every new instance of that object.
The extend
method for example in jQuery or PrototypeJS, copies all properties from the source to the destination object.
Now about the prototype
property, it is a member of function objects, it is part of the language core.
Any function can be used as a constructor, to create new object instances. All functions have this prototype
property.
When you use the new
operator with on a function object, a new object will be created, and it will inherit from its constructor prototype
.
For example:
function Foo () {}Foo.prototype.bar = true;var foo = new Foo();foo.bar; // truefoo instanceof Foo; // trueFoo.prototype.isPrototypeOf(foo); // true