JavaScript Object.create vs new<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

JavaScript Object.create vs new

Posted on: May 5, 2017

It's possible to create instance in JavaScript by using Object.create or using new called constructor function.

The Object.create creates an instance of an object with the prototype passed has first parameter. If a second parameter is provided, it will be used for this object only. This second parameter must be of type DefinedProperty.

1var MyClass1 = function () {
2 this.member1 = "m1";
5MyClass1.prototype.function1 = function () {
6 return "return from function1";
9var instance1 = new MyClass1();
10var instance2 = Object.create(MyClass1.prototype, {
11 member2: { value: "m2", writable: true },
14console.log("instance1.member1: " + instance1.member1); //m1
15console.log("instance1.function1: " + instance1.function1()); //return from function1
16console.log("instance2.member1: " + instance2.member1); //undefined
17console.log("instance2.member2: " + instance2.member2); //m2
18console.log("instance2.function1: " + instance2.function1()); //return from function1
19console.log("instance1.member2: " + instance1.member2); //undefined

This example show that the member "member1" is only present on the first instance because the second instance is created with just the prototype of MyClass1. It also shows that the instance 1 doesn't have the member2 added by the second parameter of Object.create since it is a member added to the instance 2.

Object.create and constructor function both create a new object and bot set the proto but in a different way. Object.create sets theproto to be the one passed as the first parameter. The constructor function set theproto to the type specified prototype (in the previous example MyClass1.prototype). The major difference is that Object.Create returns the new object while the constructor function return the constructor of the object or the object.

If we modified the preview code to have a console.log() in the constructor of the object, we can see that this one is executed only when using "new" and not when using Object.create.

1var MyClass1 = function () {
2 this.member1 = "m1";
3 console.log("MyClass function");
6MyClass1.prototype.function1 = function () {
7 return "return from function1";
10//var instance1 = new MyClass1();
12var instance2 = Object.create(MyClass1.prototype);

The code above doesn't execute the console.log. However, if we uncomment instance1 and comment instance2 (Object.create). We can see that it's called.

In a future article, we will see that with Object.create that it's possible to create inheritance.