我正在实现一个也可以在节点上运行的JavaScript库,我想尽可能多地使用Node的API。我的对象会发出事件,因此我找到了这个名为EventEmitter2的漂亮库,并为JavaScript重新以EventEmitter重新以EventEmitter。现在,我想为util.inherits找到同样的东西。有人听说过这样的项目吗?
您是否尝试过使用node.js实现?(它使用Object.create
,因此它可能在您关心的浏览器上使用也可能不起作用)。这是实施,来自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
}
});
};
CoffeeScript使用了另一种方法,该方法编译了
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);
您无需使用任何外部库。只需使用Javascrit。
b从
继承B.prototype = Object.create (A.prototype);
B.prototype.constructor = B;
和B的构造函数:
A.call (this, params...);
如果您知道JavaScript具有名为构造函数的属性,则避免使用它,无需隐藏或不枚举它,请避免避免。无需拥有超级属性,只需使用A.Call即可。这是JavaScript,不要像其他任何语言一样尝试使用它,因为您会失败。