简体   繁体   中英

What does it mean to call Object.create(new EventEmitter) in Node.js

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?

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.

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"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM