2015-09-27 50 views
2

我在coffeescript中創建了Point類和Vector類。兩個類都繼承MyObject類,兩個類的構造函數都使用super()。如何使用coffeescript創建另一個構造函數?

我想將點轉換爲矢量。因此,我試圖寫Vector.fromPoint()方法。該方法用作構造函數(new Vector.fromPoint(new Point(x, y)))。

但是,我不能寫在咖啡腳本。它可以用咖啡書寫嗎?我想在Vector.fromPoint構造函數中使用MyObject.constructor作爲super()。

+0

它接受的一點是另一個構造函數的構造函數。所以我想分開兩個構造函數。 fromPoint方法清楚地表明它是Point的構造函數。所以我想從point構造函數。 我無法想象如何在fromPoint中使用new。新的調用是由哪個構造函數完成的? –

回答

2

在類函數中,@是類,爲什麼不是這樣簡單的東西?

class Vector extends MyObject 
    @fromPoint: (p) -> 
     new @(p.x, p.y) 
    #... 

或者,如果你不想允許子類Vector

class Vector extends MyObject 
    @fromPoint: (p) -> 
     new Vector(p.x, p.y) 
    #... 

在你會說Vector.fromPoint(some_point),讓你Vector例如無論是哪種情況。

你也可以更換Vector的構造,這樣就可以new Vector(x, y)new Vector(some_point)

class Vector extends MyObject 
    constructor: (args...) -> 
     if(args.length == 1 && args[0] instanceof Point) 
      { @x, @y } = args[0] 
     else if(args.length == 2) 
      [ @x, @y ] = args 
     else 
      # Do whatever error handling you want here... 
     super() 
    #... 
相關問題