5

ノード上でも動作するJavaScriptライブラリを実装しており、できるだけノードのAPIを利用したい。私のオブジェクトはイベントを発行するので、JavaScript 用に EventEmitter を再実装する eventemitter2という素晴らしいライブラリを見つけました。ここで、 util.inheritsについても同じことを見つけたいと思います。誰かそのようなプロジェクトについて聞いたことがありますか?

4

2 に答える 2

8

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
    }
  });
};

もう 1 つの方法は、CoffeeScript によって使用されます。

class Super
class Sub extends Super

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);
于 2012-11-02T19:43:52.577 に答える
6

外部ライブラリを使用する必要はありません。javascritをそのまま使用してください。

BはAから継承します

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

そしてBのコンストラクターの内部:

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

javascriptにコンストラクタという名前のプロパティがあることがわかっている場合は、それを避けてください。非表示にしたり列挙したりする必要はありません。避けることは避けてください。スーパープロパティを持つ必要はありません。単にA.callを使用してください。これはjavascriptです。惨めに失敗するので、他の言語のように使用しないでください。

于 2012-11-03T12:46:16.123 に答える