【问题标题】:How do I make another constructor with coffeescript?如何使用咖啡脚本制作另一个构造函数?
【发布时间】:2015-12-24 13:54:22
【问题描述】:

我在 coffeescript 中创建了 Point 类和 Vector 类。两个类都继承了 MyObject 类,两个类的构造函数都使用 super()。

我想将 Point 转换为 Vector。因此,我尝试编写 Vector.fromPoint() 方法。该方法用作构造函数(new Vector.fromPoint(new Point(x, y)))。

但是,我无法用coffeescript 编写它。可以用coffeescript写吗?我想在 Vector.fromPoint 构造函数中使用 MyObject.constructor 作为 super()。

【问题讨论】:

  • 接受Point的构造函数是另一个构造函数。所以我想分开两个构造函数。 fromPoint 方法清楚地表明它是带有 Point 的构造函数。所以我想要 fromPoint 构造函数。我无法想象如何在 fromPoint 中使用 new。 new 调用了哪个构造函数?

标签: coffeescript


【解决方案1】:

在类函数中,@ 是类,那么为什么不像这样简单呢?

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()
     #...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多