util.inherits - alternative or workaround

后端 未结 4 766
面向向阳花
面向向阳花 2021-02-05 08:46

I am a n00b in node, and find util.inherits() very useful, except for the fact that it seems to replace the entire prototype of the original object. For instance:

4条回答
  •  清歌不尽
    2021-02-05 09:19

    I very much wanted the same thing and was unhappy with extend, so I created this extension to the already useful util.inherits method:

    var util = require('util');
    
    module.exports = {
        inherits : function(sub, sup, proto) {
            util.inherits(sub, sup);
            if (typeof proto !== 'undefined') {
                Object.keys(proto).forEach(function(key) {
                    sub.prototype[key] = proto[key];
                });
            }
        }
    };
    

    I put this in my project's ./util/index.js and then do this to use it:

    var EventEmitter = require('events').EventEmitter;
    var util = require('./util');
    
    function Foo() {
        EventEmitter.call(this);
    }
    
    util.inherits(Foo, EventEmitter, {
        bar : function(){
            console.log(this instanceof EventEmitter); // true
        }
    });
    

    Maybe I'll publish this if I find it's robust and useful more and more. I just barely implemented it myself, so I'm giving it a test run.

    Let me know what you think!

    NOTE: This does override methods on either of the classes with the ones defined in the proto hash at the end. Just be aware of that.

提交回复
热议问题