Mixin EventEmitter Methods Using __proto__

For an arbitrary object, I want to make it an EventEmitter:

var obj = {} // mixin eventemitter obj.on('event', ...) obj.emit('event') 

Also, when I type obj, I don’t want it to show EventEmitter methods as methods. ex via CLI:

 > obj {} 

So right now I am doing:

 function mixinEventEmitter(obj) { obj.__proto__ = EventEmitter.prototype return obj } 

But people say using __proto__ is an anti-pattern: Node.js is an inheritance from EventEmitter

Am I doing it right? Do you have a better way to do this? Thanks.

+4
source share
2 answers

The usual way to do this is to use util.inherits (the related documentation contains an example that you almost certainly want).

+2
source

The problem with __proto__ is not that you use prototypes instead of constructors. The problem is that this is the wrong way to use prototypes. But you do not need a prototype. You want to mix. Using __proto__ is a hack that avoids the work of creating mixin. If you want to mix, you must do it manually, without prototypes.

 var EventEmitter = require("events").EventEmitter, obj = {}; function emitter(obj) { // copy EventEmitter prototype to obj, but make properties // non-enumerable for (var prop in EventEmitter.prototype) { Object.defineProperty(obj, prop, { configurable: true, writable: true, value: EventEmitter.prototype[prop] }); } // also, make sure the following properties are hidden // before the constructor adds them ["domain", "_events", "_maxListeners"].forEach(function(prop) { Object.defineProperty(obj, prop, { configurable: true, writable: true, value: undefined }); }); // call EventEmitter constructor on obj EventEmitter.call(obj); // return the obj, which should now function as EventEmitter return obj; } emitter(obj); obj.on("event", console.log.bind(console)); obj.emit("event", "foo"); 
+1
source

Source: https://habr.com/ru/post/1436323/


All Articles