是的,您可以使用原型继承来模拟它。由于该语言是原型驱动的,因此规则非常不同,您需要对原型链等进行一些研究,但最终证明它非常有用。
查看 Node 核心中继承自 EventEmitter 的东西。它们有一个名为 util.inherits 的内置函数,该函数具有适用于更高版本的 ECMA 的实现。它看起来像这样:
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = function(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
Stream 类是一个使用示例:
https://github.com/joyent/node/blob/master/lib/stream.js#L22-29 https://github.com/joyent/node/blob/master/lib/stream.js#L22-29
var events = require('events');
var util = require('util');
function Stream() {
events.EventEmitter.call(this);
}
util.inherits(Stream, events.EventEmitter);
在coffeescript中,类编译成一组略有不同的代码,归结为这个__extends函数。我believe这将具有更多的跨浏览器兼容性,但我不记得谁不支持 Object.create。
var __hasProp = Object.prototype.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;
};