I recently stumbled upon the Object.create()
method in JavaScript, and am trying to deduce how it is different from creating a new instance of an object with
Let me try to explain (more on Blog) :
Car
constructor var Car = function(){}
, this is how things are internally:
{prototype}
hidden link to Function.prototype
which is not accessible and one prototype
link to Car.prototype
which is accessible and has an actual constructor
of Car
. Both Function.prototype and Car.prototype have hidden links to Object.prototype
.When we want to create two equivalent objects by using the new
operator and create
method then we have to do it like this: Honda = new Car();
and Maruti = Object.create(Car.prototype)
.
What is happening?
Honda = new Car();
— When you create an object like this then hidden {prototype}
property is pointed to Car.prototype
. So here, the {prototype}
of the Honda object will always be Car.prototype
— we don't have any option to change the {prototype}
property of the object. What if I want to change the prototype of our newly created object?
Maruti = Object.create(Car.prototype)
— When you create an object like this you have an extra option to choose your object's {prototype}
property. If you want Car.prototype as the {prototype}
then pass it as a parameter in the function. If you don't want any {prototype}
for your object then you can pass null
like this: Maruti = Object.create(null)
.
Conclusion — By using the method Object.create
you have the freedom to choose your object {prototype}
property. In new Car();
, you don't have that freedom.
Preferred way in OO JavaScript :
Suppose we have two objects a
and b
.
var a = new Object();
var b = new Object();
Now, suppose a
has some methods which b
also wants to access. For that, we require object inheritance (a
should be the prototype of b
only if we want access to those methods). If we check the prototypes of a
and b
then we will find out that they share the prototype Object.prototype
.
Object.prototype.isPrototypeOf(b); //true
a.isPrototypeOf(b); //false (the problem comes into the picture here).
Problem — we want object a
as the prototype of b
, but here we created object b
with the prototype Object.prototype
.
Solution — ECMAScript 5 introduced Object.create()
, to achieve such inheritance easily. If we create object b
like this:
var b = Object.create(a);
then,
a.isPrototypeOf(b);// true (problem solved, you included object a in the prototype chain of object b.)
So, if you are doing object oriented scripting then Object.create()
is very useful for inheritance.