Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Object.create and inheritance

Object.create and inheritance

Problem

What is the difference between the resulting objects in the following examples:

var EventEmitter = require('events').EventEmitter;

var oProto  = Object.create(EventEmitter.prototype);
var oProto2 = Object.create(oProto);

var oConstr  = Object.create(new EventEmitter);
var oConstr2 = Object.create(oConstr);

I suppose oConstr and oConstr2 will have any properties set in the EventEmitter constructor, but is there any other meaningful difference?

Problem courtesy of: Jacob R

Solution

Your code is misleading. you use the term oConstr when it's not a constructor function.

oProto -> EventEmitter.prototype -> Object.prototype -> null
oProto2 -> oProto -> EventEmitter.prototype -> Object.prototype -> null

var temp = new EventEmitter;

oConstr -> temp -> EventEmitter.prototype -> Object.prototype -> null
oConstr2 -> oConstr -> etc

The only difference is that temp is not just an object that inherits from EventEmitter it also has own properties augmented from the call to EventEmitter.constructor.call(temp).

I'd personally recommend you use EventEmitter.prototype and ignore new EventEmitter

Personally I don't ever inherit from EventEmitter, I mix it in

Solution courtesy of: Raynos

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Object.create and inheritance

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×