2012-05-21 3 views

答えて

23

はい、代わりにextendsを使用できます。

違いは?のは、CoffeeScriptのを見てから始めましょう:

class B extends A 

はのは、このJavaScriptがthe JavaScript the CoffeeScript compiler producesを見てみましょう:

var B, 
    __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; }; 

B = (function(_super) { 

    __extends(B, _super); 

    function B() { 
    return B.__super__.constructor.apply(this, arguments); 
    } 

    return B; 

})(A); 

ので、__extendsBA間の継承関係を宣言するのに使用されます。

のは、CoffeeScriptの中で、もう少し読み取り可能__extendsを言い換えるてみましょう:

coffee__extends = (child, parent) -> 
    child[key] = val for own key, val of parent 

    ctor = -> 
    @constructor = child 
    return 
    ctor.prototype = parent.prototype 

    child.prototype = new ctor 
    child.__super__ = parent.prototype 

    return child 

(。あなたは、これがcompiling it back to JavaScriptによって忠実に再現していることを確認することができます)

ここで何が起こっているのかです:

  1. parentに直接見つかったすべてのキーはchildに設定されています。
  2. 新しいプロトタイプコンストラクタctorが作成され、そのインスタンスのconstructorプロパティが子に設定され、そのprototypeが親に設定されます。
  3. 子クラスのprototypeは、ctorのインスタンスに設定されています。 ctorconstructorchildに設定され、ctorのプロトタイプ自体はparentです。
  4. 子クラスの__super__プロパティは、parentprototypeに設定され、CoffeeScriptのsuperキーワードで使用されます。
node's documentation

次のようにutil.inheritsを説明:

を別に1つのコンストラクタからプロトタイプメソッドを継承。 コンストラクタのプロトタイプは、 superConstructorから作成された新しいオブジェクトに設定されます。

さらに便利なように、superConstructorはconstructor.super_プロパティを使用して にアクセスできます。

結論として、CoffeeScriptのクラスを使用している場合は、util.inheritsを使用する必要はありません。単にCSがあなたに与えるツールを使用すれば、superのようなボーナスが得られます。