ca59525
ca59525

Reputation: 13

Object.create vs. Object.create() vs. Object.create(null)

var obj1 = Object.create;
console.log(typeof obj1);
var obj2 = Object.create(null);
console.log(typeof obj2);
var obj3 = Object.create();
console.log(typeof obj3);

results in the following console messages:

function 
object 
Uncaught TypeError: Object prototype may only be an Object or null: undefined

How come that the console message for obj1 and obj3 are different? What is the difference between Object.create and Object.create()?

Upvotes: 0

Views: 228

Answers (2)

Vishal Sakaria
Vishal Sakaria

Reputation: 1397

Pointy is right!

To expand on Object.create(null)

All objects in JS inherit from Object or the Object you pass into Object.create.

So for example var man = Object.create(Person.prototype)

Here man will inherit from Person and Person will inherit from Object

However if your create an object like this: Object.create(null) then the result will be a object that inherits from nothing.

So passing null results in a object without any inheritance.

Upvotes: 0

Pointy
Pointy

Reputation: 413767

Object.create without the () is just a reference to the function. With the (), it's a call to the function.

Calling Object.create() with no argument is an error, as the exception message explains. You have to pass an object, or the value null.

Upvotes: 5

Related Questions