问题__proto__
不在于您使用的是原型而不是构造函数。问题是使用原型的方法是错误的。但是你不想要原型。你想要一个mixin。Using__proto__
是一种避免创建 mixin 工作的技巧。如果你想要一个 mixin,你必须手动完成,没有原型。
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");