問題__proto__
は、コンストラクターの代わりにプロトタイプを使用していることではありません。問題は、プロトタイプの使用方法が間違っていることです。しかし、プロトタイプは必要ありません。ミックスインが必要です。Using__proto__
は、ミックスインを作成する作業を回避するハックです。ミックスインが必要な場合は、プロトタイプなしで手動で行う必要があります。
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");