Question

I've read the MDN document on Object.create. It only pointed out the scenario when the first argument is a prototype. However, I've seen some code in Node.js like this:

var events = require('events');  
var emitter = new events.EventEmitter();  
var a = Object.create(emitter);

So what does Object.create() do when its first argument is an object?

Was it helpful?

Solution

The first parameter to Object.create is always the prototype, which is always an object.

In this case it just means that the prototype happens to be created via new - no big deal. If new does (as it should) return a new object, then think of it as a one-off (or "unshared") prototype that will only be used for the new Object.create'd object.

The [prototype] of the Object.create prototype, as established by new, will also be part of the chain, as per standard rules.

See Object.create on MDN:

Object.create(proto [, propertiesObject ])

proto - The object which should be the prototype of the newly-created object.

OTHER TIPS

Using Object.create with new to create several instances can cause problems. Using new creates an object that can (and most likely) have instance specific members. If you then use that object to create several instances you will have instance specific members on the newly created object's prototype. Prototype is shared and mutating these members will mutate it for all instances. As the following example demonstrate with the food member.

var Person = function(){
  this.food=[];//every person has food
      // this should be instance specific
};
Person.prototype.eat = function(foodItem){
  this.food.push(foodItem);
};
var proto = Object.create(new Person());
var bob = Object.create(proto);
var ben = Object.create(proto);
bob.eat("Eggs");
console.log(ben.food);//=["Eggs"]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top