What is prototype property, and why is it necessary? So far, I have learnt that this provides public access to more intrinsic, and private prototype of the object; is that correct?
Also, what’s the difference between following statements?
MyConstructor.age = 30;
MyConstructor.prototype.age = 30;
In short, I need a better understanding of keyword prototype.
Thanks
“Prototype” is something that plays a role in objects.
In Javascript, everything is an object. Every object has a kind, and thus inherits the
prototypeof that kind.For example, take a simple array:
var a = []. You can make operations with it, likea.push(10). Where does thispushmethod come from? From the prototype ofArrayobject, whichais.You can add your own methods to
Arrayobjects just by defining them in theprototypeobject. For example:This way you can do something like
a.sortNum()with all arrays, even the ones created before you defined thesortNummethod.(Note: for compatibility reasons, it’s usually not recommended to extend the prototype of native objects like
Arrays. But this particular example is usually a welcome addition, as well as normalizing methods likemapandforEachfor older browsers.)(Just never ever extend
Object.prototype! Unless you don’t care to mess upfor...instatements, theinoperator and these sort of cases.)If you want to define your own classes, like the name
MyConstructorsuggests, you’ll have to define itsprototypeto define the methods for all the instances of that class:You can define more than just functions in
prototypes, too:Watch out when you do this to define “default” object values, because changing it may cause a change in all instances of that class.
But this comes handy with
Object.defineProperty:(Unfortunately, IE<9 allows this only for DOM objects…)
When you define
MyConstructor.age = 30instead, what you’re actually doing is defining a member of the functionMyConstructor, somc.agewould be undefined. Every instance ofMyConstructorinherits the methods and members defined inMyConstructor.prototype, not the ones of the functionMyConstructor.There’s much more to say, actually. Objects can be of a subclass of another class, thus inheriting the
prototypeof the superclass, too. For example,document.bodyis an instance ofHTMLBodyElement, which is a subclass ofHTMLElement, which is a subclass ofElementand so on, until you getObjectas the upmost superclass. So,document.bodyinherits all the methods defined in the prototype ofHTMLBodyElement,HTMLElement,ElementandObject. This is called the prototype chain.Doing the same with custom objects is a bit tricky: