util.inherits - alternative or workaround

后端 未结 4 760
面向向阳花
面向向阳花 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:08

    It does not make sense that you have to declare your prototype after util.inherits(). My guess is util.inherits originated as an internal-use-only method, tailored only for the limited internal use-cases it was initially intended for, which at some point got published for general usage. The util module is written in pure JS, so it is very easy to implement your own version of util.inherit that preserves your prototype. Here's the original util.inherit source:

    exports.inherits = function(ctor, superCtor) {
      ctor.super_ = superCtor;
      ctor.prototype = Object.create(superCtor.prototype, {
        constructor: {
          value: ctor,
          enumerable: false,
          writable: true,
          configurable: true
        }
      });
    };
    

    As for the multiple inheritance, that's going to be a much more difficult problem to tackle, as Javascript's prototype inheritance is not really suited for multiple inheritance at all. Each instance has only a single internal [[Prototype]] property, which is used to look up members that are not found in the actual instance. You could merge the prototypes of two separate "parent classes" into a single prototype, but you will then lose the inheritance to their parents, and you will lose the ability to change the parent prototype and have all children see the change.

提交回复
热议问题