seb*_*piq 4 javascript node.js
我正在实现一个也可以在节点上运行的JavaScript库,我想尽可能多地使用node的API.我的对象发出事件,所以我发现了这个名为eventemitter2的漂亮库,它为JavaScript重新实现了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
}
});
};
Run Code Online (Sandbox Code Playgroud)
CoffeeScript使用另一种方法编译
class Super
class Sub extends Super
Run Code Online (Sandbox Code Playgroud)
至
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);
Run Code Online (Sandbox Code Playgroud)
您不需要使用任何外部库.只需按原样使用javascrit.
B继承自A
B.prototype = Object.create (A.prototype);
B.prototype.constructor = B;
Run Code Online (Sandbox Code Playgroud)
在B的构造函数中:
A.call (this, params...);
Run Code Online (Sandbox Code Playgroud)
如果你知道javascript有一个名为constructor的属性,那么避免它,不需要隐藏或不枚举它,避免避免.无需拥有超级属性,只需使用A.call即可.这是javascript,不要试图像任何其他语言一样使用它,因为你将失败.
| 归档时间: |
|
| 查看次数: |
2396 次 |
| 最近记录: |