Function Constructor, Prototype, and mix

ref – http://a-developer-life.blogspot.com/2011/11/7-ways-to-create-objects-in-javascript.html

Creates a Person object, which has attribute name, and function getName.

The constructor pattern is compact, reusable and gives a classical OO syntax.

However, here’s the problem:

In our example the field getName is a function.

In Javascript functions are objects. Thus, 10 object will have 10 function. And this means we define ten extra objects.

Escalate this to a thousand and realize how much memory is being wasted!

It would be nice if all instances of Person share the same getName object, since this holds behavior and not data.

Prototype

Functions are very special in Javascript. They are objects, they can create other objects and they automatically get a field called prototype.

A prototype is a plain object with a single field, called constructor, pointing to the function itself.
What makes it special is that every object created through a function inherits the function’s prototype.

Thus, personOne and personTwo will both have attribute name initialized to “Diego”. Therefore, all instances share the same fields.

Function constructor gives you objects with the instantiation’s own functions, but numerous instances take up too much space because each function is like an object.

Prototype let’s you escape that by using the prototype property. This let’s the instantiations share attributes and functions.

The function/prototype combination let’s you take advantage of both approaches.

While sharing behavior (the getName function), each object has its own data and state in the attribute ‘name’.