I am implementing a JavaScript library that can also run on node, and I'd like to use node's API as much as possible. My objects emit events, so I found this nice library called eventemitter2, and which reimplements EventEmitter for JavaScript. Now I'd like to find the same for util.inherits. Has anybody heard about such a project ?
Have you tried using the Node.js implementation? (It uses Object.create
, so it may or may not work on 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);
You don't need to use any external library. Just use javascrit as is.
B inherits from A
B.prototype = Object.create (A.prototype);
B.prototype.constructor = B;
And inside the constructor of B:
A.call (this, params...);
If you know that javascript has a property named constructor, then avoid it, no need to hide or not enumerate it, avoid avoid avoid. No need to have a super property, simply use A.call. This is javascript, don't try to use it like any other language because you will miserably fail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With