413

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 new SomeFunction(), and when you would want to use one over the other.

Consider the following example:

var test = {
  val: 1,
  func: function() {
    return this.val;
  }
};
var testA = Object.create(test);

testA.val = 2;
console.log(test.func()); // 1
console.log(testA.func()); // 2

console.log('other test');
var otherTest = function() {
  this.val = 1;
  this.func = function() {
    return this.val;
  };
};

var otherTestA = new otherTest();
var otherTestB = new otherTest();
otherTestB.val = 2;
console.log(otherTestA.val); // 1 
console.log(otherTestB.val); // 2

console.log(otherTestA.func()); // 1
console.log(otherTestB.func()); // 2

Notice that the same behaviour is observed in both cases. It seems to me that the primary differences between these two scenarios are:

  • The object used in Object.create() actually forms the prototype of the new object, whereas in the new Function() from the declared properties/functions do not form the prototype.
  • You cannot create closures with the Object.create() syntax as you would with the functional syntax. This is logical given the lexical (vs block) type scope of JavaScript.

Are the above statements correct? And am I missing something? When would you use one over the other?

EDIT: link to jsfiddle version of above code sample: http://jsfiddle.net/rZfYL/

BanksySan
  • 24,077
  • 27
  • 94
  • 189
Matt
  • 38,720
  • 26
  • 105
  • 143
  • 2
    See also [Using “Object.create” instead of “new”](http://stackoverflow.com/q/2709612/1048572) – Bergi Jul 24 '15 at 15:04
  • [What is the difference between `new Object()` and object literal notation?](https://stackoverflow.com/questions/4597926/) is related too, which is comparing new, create and just `{}` – AaA Jul 02 '20 at 03:28

11 Answers11

463

Very simply said, new X is Object.create(X.prototype) with additionally running the constructor function. (And giving the constructor the chance to return the actual object that should be the result of the expression instead of this.)

That’s it. :)

The rest of the answers are just confusing, because apparently nobody else reads the definition of new either. ;)

Lyubomir
  • 17,533
  • 4
  • 51
  • 65
Evi1M4chine
  • 6,214
  • 1
  • 22
  • 16
  • 25
    +1 Simplicity and clarity! (Though the Object.create(null) seems a nice option - maybe should mention that). – user949300 Sep 03 '14 at 04:15
  • 1
    keep it simple that's the way to go – Bill May 26 '16 at 12:12
  • That just leaves the question of "wait, so _functions_ have prototypes _too_? What's the relationship between those and _object_ prototypes?" – Qwertie May 31 '16 at 22:46
  • 4
    @Qwertie: In JS, *everything* is an object. :) They copied that from Java, who copied it from SmallTalk, who went all the way to the end with it. It’s a nice case of “emergence”, making life easier in general. – Evi1M4chine Jun 30 '16 at 14:54
  • 1
    @Evi1M4chine actually in Java, functions are not objects (and neither are primitives, for that matter)... and objects don't have prototypes, so the comparison seems un-fitting. The fact that JS works differently than other popular OO languages is a major source of confusion (and it doesn't help that browsers don't provide an easy way to visualize the network of objects including functions and prototypes). P.S. I found this link helpful : https://davidwalsh.name/javascript-objects-deconstruction – Qwertie Jul 02 '16 at 04:27
  • 1
    @Qwertie: I didn’t say that Java fully *did* follow that philosophy. They had the _philosophy_. They just half-assed it. :) But SmallTalk certainly followed it. … And OOP does not equal class-based OOP.. JS is prototype-based OOP, but they all have OOP in common. In fact JS’s OOP philosophy is much cleaner, more elegant and more universal than the class-based approach. They just failed to implement it nicely too. (JavaScript 2 was supposed to solve all that, and would have been quite nice. WebAssembly made all of it moot. :) – Evi1M4chine Nov 29 '16 at 00:38
  • still don't understand why constructors HAVE to be functions. isn't their only job to have a .prototype to set __proto__ of instance to? why is there such a need to couple initialization into it? Such a pain to create your own object models if your constructors cant have their own prototype(like Object) because they must be Functions(that only accomodate Object). – Dmitry Mar 30 '18 at 10:59
252

The object used in Object.create actually forms the prototype of the new object, where as in the new Function() form the declared properties/functions do not form the prototype.

Yes, Object.create builds an object that inherits directly from the one passed as its first argument.

With constructor functions, the newly created object inherits from the constructor's prototype, e.g.:

var o = new SomeConstructor();

In the above example, o inherits directly from SomeConstructor.prototype.

There's a difference here, with Object.create you can create an object that doesn't inherit from anything, Object.create(null);, on the other hand, if you set SomeConstructor.prototype = null; the newly created object will inherit from Object.prototype.

You cannot create closures with the Object.create syntax as you would with the functional syntax. This is logical given the lexical (vs block) type scope of JavaScript.

Well, you can create closures, e.g. using property descriptors argument:

var o = Object.create({inherited: 1}, {
  foo: {
    get: (function () { // a closure
      var closured = 'foo';
      return function () {
        return closured+'bar';
      };
    })()
  }
});

o.foo; // "foobar"

Note that I'm talking about the ECMAScript 5th Edition Object.create method, not the Crockford's shim.

The method is starting to be natively implemented on latest browsers, check this compatibility table.

jithinkmatthew
  • 718
  • 7
  • 15
Christian C. Salvadó
  • 723,813
  • 173
  • 899
  • 828
  • 2
    @CMS 2 questions. 1) Does the scope chain on Object.create(null) still terminate at the global scope (such as 'window' in a browser), or does it terminate on itself? 2) It is still not clear to me why Object.create was introduced (e.g. what feature was missing that this addressed?) and why one would use it instead of new Function(); – Matt Nov 12 '10 at 16:30
  • 10
    @Matt, 1) the scope chain is not really a related concept here, scope chain is related to **identifier resolution**, e.g.: how `foo;` is resolved in the current *lexical environment*. 2) To provide an easy way to implement inheritance, it's a really powerful construct. IMO I would use it because it's really simple and lightweight, but for production code, we still need to wait some time until ES5 is supported widely. About missing features, the fact of creating a "pristine" object, `Object.create(null);` was missing, it's really useful to implement reliable hash-table-like objects... – Christian C. Salvadó Nov 12 '10 at 16:38
  • @CMS Thanks. So simply when you create a object by using 'Object.create',you get the ability to select the object that should be its prototype. – Anshul Sep 02 '14 at 18:52
  • @CMS O.K., so `Object.create(null)` means you don't have to use `hasOwnProperty()` crap when iterating cause it inherits none??? I like that - thanks. Of course, everybody is _still_ going to do `hasOwnProperty` since not everybody will use `Object.create(null)` so I'm not sure it's a real benefit... So far I have found the other "benefits" of `Object.create()` completely unconvincing. – user949300 Sep 03 '14 at 04:12
214

Here are the steps that happen internally for both calls:
(Hint: the only difference is in step 3)


new Test():

  1. create new Object() obj
  2. set obj.__proto__ to Test.prototype
  3. return Test.call(obj) || obj; // normally obj is returned but constructors in JS can return a value

Object.create( Test.prototype )

  1. create new Object() obj
  2. set obj.__proto__ to Test.prototype
  3. return obj;

So basically Object.create doesn't execute the constructor.

Ray Hulha
  • 8,891
  • 5
  • 41
  • 44
  • @Ray so using object.create we font have the properties of function mentioned in constructor function? –  Feb 21 '17 at 12:28
  • @sortednoun as long as the properties are private and not specified on the prototype, **yes, they won't be inherited and you won't have them in the new object** (and, I would add, you can expect to get eventual prototyped properties from the parent, just when the parent constructor has been execute at least once). – Kamafeather Jul 25 '17 at 16:52
  • As with most constructor functions the methods are defined within the returned object, `new` basically has all functions duplicated, while `Object.create` doesn't. – SparK Apr 07 '20 at 19:59
63

Let me try to explain (more on Blog) :

  1. When you write Car constructor var Car = function(){}, this is how things are internally: A diagram of prototypal chains when creating javascript objects We have one {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.
  2. 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).A diagram of prototypal chains for differing object creation methods 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.

limeandcoconut
  • 417
  • 6
  • 20
Anshul
  • 8,324
  • 9
  • 53
  • 70
  • So, it is somewhat similar to object creation without constructor invocation? We will enjoy all the benefits of the class. The obj instanceof Class will also be true. But we are not invoking the Class function via new. – Praveen Mar 30 '16 at 08:49
  • @Anshul You said that `a.isPrototypeOf(b);` will return `false` which is right, because both Objects are different and pointing to different memory. The correct way to do this with the `new` operator is here. - https://jsfiddle.net/167onunp/ . – Sagar Karira Nov 10 '16 at 11:29
  • Why wouldn't you just set the prototype property of b to a, instead of doing this? – Amnestic Dec 03 '16 at 19:09
  • Liked the article on your blog too. Helped me understand the concept much better. Thank you. – steady_daddy Aug 09 '17 at 09:59
  • 1
    The conclusion says it all. – HalfWebDev Aug 14 '17 at 11:20
  • Note that on all modern JavaScript implementations the 'hidden' `[[Prototype]]` can be accessed as `__proto__` (non-standard) and with the `Object.getPrototypeOf` function. – yyny Oct 31 '17 at 23:51
47

This:

var foo = new Foo();

and

var foo = Object.create(Foo.prototype);

are quite similar. One important difference is that new Foo actually runs constructor code, whereas Object.create will not execute code such as

function Foo() {
    alert("This constructor does not run with Object.create");
}

Note that if you use the two-parameter version of Object.create() then you can do much more powerful things.

Leopd
  • 37,882
  • 29
  • 117
  • 156
  • 1
    Great explanation. Might I add, using `Object.create` in its simplest form like this allows you to omit constructor functions from your code while taking advantage of prototype inheritance. – Ricky Boyce Nov 19 '15 at 04:38
23

The difference is the so-called "pseudoclassical vs. prototypal inheritance". The suggestion is to use only one type in your code, not mixing the two.

In pseudoclassical inheritance (with "new" operator), imagine that you first define a pseudo-class, and then create objects from that class. For example, define a pseudo-class "Person", and then create "Alice" and "Bob" from "Person".

In prototypal inheritance (using Object.create), you directly create a specific person "Alice", and then create another person "Bob" using "Alice" as a prototype. There is no "class" here; all are objects.

Internally, JavaScript uses "prototypal inheritance"; the "pseudoclassical" way is just some sugar.

See this link for a comparison of the two ways.

user1931858
  • 9,266
  • 1
  • 15
  • 5
21
function Test(){
    this.prop1 = 'prop1';
    this.prop2 = 'prop2';
    this.func1 = function(){
        return this.prop1 + this.prop2;
    }
};

Test.prototype.protoProp1 = 'protoProp1';
Test.prototype.protoProp2 = 'protoProp2';
var newKeywordTest = new Test();
var objectCreateTest = Object.create(Test.prototype);

/* Object.create   */
console.log(objectCreateTest.prop1); // undefined
console.log(objectCreateTest.protoProp1); // protoProp1 
console.log(objectCreateTest.__proto__.protoProp1); // protoProp1

/* new    */
console.log(newKeywordTest.prop1); // prop1
console.log(newKeywordTest.__proto__.protoProp1); // protoProp1

Summary:

1) with new keyword there are two things to note;

a) function is used as a constructor

b) function.prototype object is passed to the __proto__ property ... or where __proto__ is not supported, it is the second place where the new object looks to find properties

2) with Object.create(obj.prototype) you are constructing an object (obj.prototype) and passing it to the intended object ..with the difference that now new object's __proto__ is also pointing to obj.prototype (please ref ans by xj9 for that)

Pedro del Sol
  • 2,774
  • 9
  • 40
  • 49
user3124360
  • 343
  • 4
  • 10
20

Object creation variants.


Variant 1 : 'new Object()' -> Object constructor without arguments.

var p1 = new Object(); // 'new Object()' create and return empty object -> {}

var p2 = new Object(); // 'new Object()' create and return empty object -> {}

console.log(p1); // empty object -> {}

console.log(p2); // empty object -> {}

// p1 and p2 are pointers to different objects
console.log(p1 === p2); // false

console.log(p1.prototype); // undefined

// empty object which is in fact Object.prototype
console.log(p1.__proto__); // {}

// empty object to which p1.__proto__ points
console.log(Object.prototype); // {}

console.log(p1.__proto__ === Object.prototype); // true

// null, which is in fact Object.prototype.__proto__
console.log(p1.__proto__.__proto__); // null

console.log(Object.prototype.__proto__); // null

enter image description here


Variant 2 : 'new Object(person)' -> Object constructor with argument.

const person = {
    name: 'no name',
    lastName: 'no lastName',
    age: -1
}

// 'new Object(person)' return 'person', which is pointer to the object ->
//  -> { name: 'no name', lastName: 'no lastName', age: -1 }
var p1 = new Object(person);

// 'new Object(person)' return 'person', which is pointer to the object ->
//  -> { name: 'no name', lastName: 'no lastName', age: -1 }
var p2 = new Object(person);

// person, p1 and p2 are pointers to the same object
console.log(p1 === p2); // true
console.log(p1 === person); // true
console.log(p2 === person); // true

p1.name = 'John'; // change 'name' by 'p1'
p2.lastName = 'Doe'; // change 'lastName' by 'p2'
person.age = 25; // change 'age' by 'person'

// when print 'p1', 'p2' and 'person', it's the same result,
// because the object they points is the same
console.log(p1); // { name: 'John', lastName: 'Doe', age: 25 }
console.log(p2); // { name: 'John', lastName: 'Doe', age: 25 }
console.log(person); // { name: 'John', lastName: 'Doe', age: 25 }

enter image description here


Variant 3.1 : 'Object.create(person)'. Use Object.create with simple object 'person'. 'Object.create(person)' will create(and return) new empty object and add property '__proto__' to the same new empty object. This property '__proto__' will point to the object 'person'.

const person = {
        name: 'no name',
        lastName: 'no lastName',
        age: -1,
        getInfo: function getName() {
           return `${this.name} ${this.lastName}, ${this.age}!`;
    }
}

var p1 = Object.create(person);

var p2 = Object.create(person);

// 'p1.__proto__' and 'p2.__proto__' points to
// the same object -> 'person'
// { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
console.log(p1.__proto__);
console.log(p2.__proto__);
console.log(p1.__proto__ === p2.__proto__); // true

console.log(person.__proto__); // {}(which is the Object.prototype)

// 'person', 'p1' and 'p2' are different
console.log(p1 === person); // false
console.log(p1 === p2); // false
console.log(p2 === person); // false

// { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
console.log(person);

console.log(p1); // empty object - {}

console.log(p2); // empty object - {}

// add properties to object 'p1'
// (properties with the same names like in object 'person')
p1.name = 'John';
p1.lastName = 'Doe';
p1.age = 25;

// add properties to object 'p2'
// (properties with the same names like in object 'person')
p2.name = 'Tom';
p2.lastName = 'Harrison';
p2.age = 38;

// { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
console.log(person);

// { name: 'John', lastName: 'Doe', age: 25 }
console.log(p1);

// { name: 'Tom', lastName: 'Harrison', age: 38 }
console.log(p2);

// use by '__proto__'(link from 'p1' to 'person'),
// person's function 'getInfo'
console.log(p1.getInfo()); // John Doe, 25!

// use by '__proto__'(link from 'p2' to 'person'),
// person's function 'getInfo'
console.log(p2.getInfo()); // Tom Harrison, 38!

enter image description here


Variant 3.2 : 'Object.create(Object.prototype)'. Use Object.create with built-in object -> 'Object.prototype'. 'Object.create(Object.prototype)' will create(and return) new empty object and add property '__proto__' to the same new empty object. This property '__proto__' will point to the object 'Object.prototype'.

// 'Object.create(Object.prototype)' :
// 1. create and return empty object -> {}.
// 2. add to 'p1' property '__proto__', which is link to 'Object.prototype'
var p1 = Object.create(Object.prototype);

// 'Object.create(Object.prototype)' :
// 1. create and return empty object -> {}.
// 2. add to 'p2' property '__proto__', which is link to 'Object.prototype'
var p2 = Object.create(Object.prototype);

console.log(p1); // {}

console.log(p2); // {}

console.log(p1 === p2); // false

console.log(p1.prototype); // undefined

console.log(p2.prototype); // undefined

console.log(p1.__proto__ === Object.prototype); // true

console.log(p2.__proto__ === Object.prototype); // true

enter image description here


Variant 4 : 'new SomeFunction()'

// 'this' in constructor-function 'Person'
// represents a new instace,
// that will be created by 'new Person(...)'
// and returned implicitly
function Person(name, lastName, age) {

    this.name = name;
    this.lastName = lastName;
    this.age = age;

    //-----------------------------------------------------------------
    // !--- only for demonstration ---
    // if add function 'getInfo' into
    // constructor-function 'Person',
    // then all instances will have a copy of the function 'getInfo'!
    //
    // this.getInfo: function getInfo() {
    //  return this.name + " " + this.lastName + ", " + this.age + "!";
    // }
    //-----------------------------------------------------------------
}

// 'Person.prototype' is an empty object
// (before add function 'getInfo')
console.log(Person.prototype); // Person {}

// With 'getInfo' added to 'Person.prototype',
// instances by their properties '__proto__',
// will have access to the function 'getInfo'.
// With this approach, instances not need
// a copy of the function 'getInfo' for every instance.
Person.prototype.getInfo = function getInfo() {
    return this.name + " " + this.lastName + ", " + this.age + "!";
}

// after function 'getInfo' is added to 'Person.prototype'
console.log(Person.prototype); // Person { getInfo: [Function: getInfo] }

// create instance 'p1'
var p1 = new Person('John', 'Doe', 25);

// create instance 'p2'
var p2 = new Person('Tom', 'Harrison', 38);

// Person { name: 'John', lastName: 'Doe', age: 25 }
console.log(p1);

// Person { name: 'Tom', lastName: 'Harrison', age: 38 }
console.log(p2);

// 'p1.__proto__' points to 'Person.prototype'
console.log(p1.__proto__); // Person { getInfo: [Function: getInfo] }

// 'p2.__proto__' points to 'Person.prototype'
console.log(p2.__proto__); // Person { getInfo: [Function: getInfo] }

console.log(p1.__proto__ === p2.__proto__); // true

// 'p1' and 'p2' points to different objects(instaces of 'Person')
console.log(p1 === p2); // false

// 'p1' by its property '__proto__' reaches 'Person.prototype.getInfo' 
// and use 'getInfo' with 'p1'-instance's data
console.log(p1.getInfo()); // John Doe, 25!

// 'p2' by its property '__proto__' reaches 'Person.prototype.getInfo' 
// and use 'getInfo' with 'p2'-instance's data
console.log(p2.getInfo()); // Tom Harrison, 38!

enter image description here

Ted
  • 655
  • 8
  • 7
11

Internally Object.create does this:

Object.create = function (o) {
    function F() {}
    F.prototype = o;
    return new F();
};

The syntax just takes away the illusion that JavaScript uses Classical Inheritance.

xj9
  • 3,086
  • 2
  • 20
  • 22
  • 25
    The ECMAScript 5 [`Object.create`](http://sideshowbarker.github.com/es5-spec/#x15.2.3.5) method, does a lot more than that, you can define properties by *property descriptors* and you can create an object that doesn't inherit from anything (`Object.create(null);`), this type of shims should be avoided because you can't really emulate that behavior on ES3. [More info](http://stackoverflow.com/questions/3830800/object-defineproperty-in-es5/3844768#3844768) – Christian C. Salvadó Nov 12 '10 at 16:24
  • Agree with @CMS but in general, it is simple polyfill for `Object.create`. – cn007b Jul 27 '17 at 21:02
10

Accordingly to this answer and to this video new keyword does next things:

  1. Creates new object.

  2. Links new object to constructor function (prototype).

  3. Makes this variable point to the new object.

  4. Executes constructor function using the new object and implicit perform return this;

  5. Assigns constructor function name to new object's property constructor.

Object.create performs only 1st and 2nd steps!!!

cn007b
  • 14,506
  • 6
  • 48
  • 62
0

Object.create(Constructor.prototype) is the part of new Constructor

this is new Constructor implementation

// 1. define constructor function

      function myConstructor(name, age) {
        this.name = name;
        this.age = age;
      }
      myConstructor.prototype.greet = function(){
        console.log(this.name, this.age)
      };

// 2. new operator implementation

      let newOperatorWithConstructor = function(name, age) {
        const newInstance = new Object(); // empty object
        Object.setPrototypeOf(newInstance, myConstructor.prototype); // set prototype

        const bindedConstructor = myConstructor.bind(newInstance); // this binding
        bindedConstructor(name, age); // execute binded constructor function

        return newInstance; // return instance
      };

// 3. produce new instance

      const instance = new myConstructor("jun", 28);
      const instance2 = newOperatorWithConstructor("jun", 28);
      console.log(instance);
      console.log(instance2);
      

new Constructor implementation contains Object.create method

      newOperatorWithConstructor = function(name, age) {
        const newInstance = Object.create(myConstructor.prototype); // empty object, prototype chaining

        const bindedConstructor = myConstructor.bind(newInstance); // this binding
        bindedConstructor(name, age); // execute binded constructor function

        return newInstance; // return instance
      };

      console.log(newOperatorWithConstructor("jun", 28));
Jun
  • 1
  • 1
  • 2