JavaScript Object prototypes

Today I will give you a small introduction into javascript and prototype. Because this blog is mainly about .Net I will try to compare it with C#.

First lets start with the basics.
Every JavaScript object has a prototype, the prototype is also an object and can contain everything and nothing :).
All JavaScript object inherit their properties and methods from their prototype.
This behavior is similiar like the C# object.

For example we have the following code:
image
A new object from Cat gets created and then we call the function miau. The miau function is not defined in the Cat itself, but in the prototype object in Cat. As we learned previously the Cat function inherits the properties and methods from prototype.
When calling the miau function defined in the prototype, the runtime looks up the function in the maunzi object, when there is no, it will look into the Cat.prototype object (where it’s actually is), then in the deep Object.prototype and if the function or property is not found in all of these it will return the typical undefined.
image

With this functionaly you can extend the base class, but you can inherit from Cat too and create a more specialized cat (for example a persian cat).
You just have to create a new PersianCat function and then set PersianCat.prototype to an instance of Cat.

To summarize some efforts of using prototype:
- implement inheritance (PersianCat inherits Cat)
- prototype functions are “static”, they get only one time initialized and not every time you create a new instance with “= new”
- add properties/functions to an already existing instance

Sure this is just a quick overview and you can dive deep into this topic, but for this I added the sources where you can read more about this :)

Sources:
http://molily.de/js/organisation-instanzen.html by molily (german)
http://www.w3schools.com/js/js_object_prototypes.asp (english)
http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work (english)


Posted Jan 22 2016, 05:35 PM by Holger Vetter

Comments

Butterfly wrote re: JavaScript Object prototypes
on 03-22-2016 13:18

I'm quite pleased with the inriomatfon in this one. TY!

developers.de is a .Net Community Blog powered by daenet GmbH.