Most of us must have seen object creation using two methods, Object.create and new operator). But some of you must have wondered what the difference is between the two methods. Let's dive into the them and outline the differences.
Consider the below code snippet.
function Animal()
{
this.name = null;
}
Animal.prototype.getName = function()
{
return this.name;
}
It's a pretty simple snippet. We have defined Animal constructor which has a property and a method. Now we will create object using the two methods.
Here is the object creation using
Object.create
Syntax:
Object.create
(proto, objectProperties)Too theoretical....now it's time for action.
var animalObj = Object.create(Animal.prototype)
Internally,
__proto__
property is created in an object and Animal.prototype
is assigned to it. So the object diagram will look like this:
The animalObj will not have any property/function as its own property.
We will now use
new
operator. It does following things:__proto__
property and assigns parent object prototype to itLets take below example and understand what is happening here
var animalObj = new Animal();
We are creating animal object from Animal constructor
Following steps are happening while using new keyword along with constructor
new
operator first creates empty object. We can safely assume it is creating empty object internallyvar obj = {};
obj.__proto__= Animal.prototype
Animal.call(obj)
animalObj
So whatever script is written in Animal constructor will run. This is where the major difference comes in because if we are defining n number of variables/function using
in constructor, all variables/functions will be assigned to newly created object as its own property, which may sometimes consume memory depending on the use case. this
So in this case object structure would look like this.
Check this out,
animalObj
contains the name
property. which is its own property.In the era of modern Javascript frameworks if anyone is still using vanilla Javascript for inheritance then it's better to useto extend one class from another, as it does not create unnecessary object variable in prototype object.Object.create
I hope that this post has been informative for you.