2012-05-21 48 views

回答

23

是的,您可以使用extends來代替它。

至於差異?讓我們先來看看CoffeeScript的:

class B extends A 

讓我們來看看the JavaScript the CoffeeScript compiler produces爲這個JavaScript:

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

所以,__extends用於聲明BA之間的傳承關係。

讓我們重申__extends多一點可讀,在CoffeeScript中:

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的實例。 ctorconstructor將被設置爲child,並且ctor的原型本身是parent
  4. 子類的__super__屬性設置爲parentprototype,供CoffeeScript的super關鍵字使用。

node's documentation描述util.inherits如下:

繼承從一個構造原型方法到另一個。 構造函數的原型將被設置爲從 superConstructor創建的新對象。

作爲額外的便利,superConstructor將通過constructor.super_屬性訪問 。

總之,如果您使用CoffeeScript的類,則不需要使用util.inherits;只需使用CS爲您提供的工具,即可獲得super關鍵字等獎金。

相關問題