Looking for a JavaScript implementation of node "util.inherits"

I am implementing a JavaScript library that can also work on node, and I would like to use the node API as much as possible. My objects emit events, so I found this pretty library called eventemitter2 and which updates EventEmitter for JavaScript. Now I would like to find the same for util.inherits . Has anyone heard of such a project?

+4
source share
2 answers

Have you tried using the implementation of Node.js? (It uses Object.create , so it may or may not work in the browsers you care about ). Here's the implementation, from https://github.com/joyent/node/blob/master/lib/util.js :

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

Another method is used by CoffeeScript, which compiles

 class Super class Sub extends Super 

to

 var Sub, Super, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; Super = (function() { function Super() {} return Super; })(); Sub = (function(_super) { __extends(Sub, _super); function Sub() { return Sub.__super__.constructor.apply(this, arguments); } return Sub; })(Super); 
+8
source

You do not need to use an external library. Just use javascrit as is.

B inherits from A

 B.prototype = Object.create (A.prototype); B.prototype.constructor = B; 

And inside constructor B:

 A.call (this, params...); 

If you know that javascript has a property called constructor, then avoid it, there is no need to hide or not list it, avoiding this. No need to have a super property, just use A.call. This is javascript, do not try to use it like any other language, because you will fail.

+5
source

Source: https://habr.com/ru/post/1443729/


All Articles