It is safe to say,
An object is a collection of properties, and a property is an association between a name (or key) and a value. Value can be anything, it can be a function (method) or even another object.
There are five patterns via which we can create Objects.
· Constructor Pattern
· Factory Pattern
· Prototype Pattern
· Dynamic Prototype Pattern
· Using Object.create() method
As we can see in the example above, ‘carfactory’ function acts as an object creation factory function, which on being invoked every time, returns a new object.
In constructor pattern, object type is defined by a constructor function and is an object instance is created using ‘new’ keyword.
As we can also observe, property of an object can also hold another object, like Car.engineSpec is accepting another object of type Engine and its property name can be accessed as well.
As we can see, the object type has property called ‘prototype’ attached to it and the parameters defined are store in that space.
However, the value of parameters defined are default and can be overridden by creation of a fresh object. Have a look:
It will print ‘Ram’ as it is stored as a default. We will explore this concept more in Prototypical inheritance.
Disadvantage: This approach can become cumbersome.
Dynamic Prototype pattern
The point to note here is, it uses the same Constructor pattern discussed above, however, while creation of an object, it will check if ‘printDetails’ function is available on ‘dynamicPerson’, and if not, it will create this function on dynamicPerson’s prototype. However, from next object creation, this printDetails function will always be available in the shared space called ‘prototype’.
Using Object.create() method
With ECMA5, a new method was introduced for creation of Objects, i.e. Object.create(). Calling this method creates an object, and prototype of this object is the first argument of ‘create. function.
Whenever, we try to seek a property on a JS object, the property will be sought not only on the object but also prototype of an object, prototype of the prototype (since, prototype can itself be an object, as seen in example of Object.create()), and so on until we get the property with matching name or we reach end of this chain.
Going ahead with last example,
Now, we can clearly see, how the chain works. If a property is present on object, its value will be retrieved from the object and no look up will be performed, however, if it is not present, the look up will happen till the top of chain is reached, in case property is not present.
So, if we try to print details of ‘anotherObj’, we can see, it is created from an object which in return is created from ‘Object’. The prototype chain of an object can be accessed using the keyword ‘__proto__’.
‘__proto__’ means parent/creator.
In example above, ‘temp’ will have access to all the methods and properties defined on its parent object’s prototype.