How should you inherit from EventEmitter in node?

前端 未结 4 446
无人共我
无人共我 2020-12-09 20:55

I was reading over this small article to understand inheriting from EventEmitter, but I\'m a little confused.

He does this:

function Doo         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 21:31

    Why does he manually invoke the EventEmitter constructor with his own constructor's this?

    This is necessary to make sure whatever code is in the EventEmitter constructor function is executed. Some classes might not do anything interesting in the constructor, but others will have important code there, so you should always do this to make sure that code runs the same way it would run if you had just made a new EventEmitter directly with var emitter = new EventEmitter;

    In some languages (such as Java) this "constructor chaining" type behavior is implicit, but in JavaScript it must be explicitly done.

    Exactly how to set up inheritance in JavaScript comes down to an "it's complicated" answer and others can probably do it more justice than I. There are also several viable variations and people differ on which is preferable. However, FYI the source for util.inherits is here and the best in-depth examination of all the flavors of doing this I have seen is in this video: Douglas Crockford: Advanced JavaScript. Basically, watch that in it's entirety periodically until it sinks in.

    Places to look for reference. If you fully understand how all these works, you've mastered it (it still turns my brain into a pretzel at some point along the way)

    • Backbone's extend helper function (which is Backbone.Model.extend, Backbone.View.extend, etc)
    • CoffeeScript's class support
    • node.js's util.extend

提交回复
热议问题