Check if object is instance of EventEmitter

♀尐吖头ヾ 提交于 2019-12-13 05:33:26

问题


I am a looking for a way, other than duck typing, to discover if an object inherits from EventEmitter

https://nodejs.org/api/events.html

I suppose I could just check if the object has a couple of those functions that event emitters have been this is just dirty.

Is there a better way to do this with Node.js? Also, if there is a way to determine if something is a stream on top of being an event emitter, that would be useful too.


回答1:


To check if an object is an instance of an EventEmmitter you can compare it with the EventEmitter from within node. Just require the "events" module which will expose an EventEmmitter.

I found and modified a little snippet for you:

var http = require("http");

http.get("http://nodejs.org/", function (res) {
    // res is an EventEmitter that represents the HTTP response
    console.log(res instanceof require("events").EventEmitter); // true
    console.log(typeof res); // object
});


来源:https://stackoverflow.com/questions/36232312/check-if-object-is-instance-of-eventemitter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!