在扩展本机类的ScalaJS类中调用重载的超级构造函数

时间:2016-03-05 23:54:45

标签: javascript scala scala.js

我有这个JavaScript类/构造函数:

function Grid(size, tileFactory, previousState, over, won) {
    this.size        = size;
    this.tileFactory = tileFactory;
    this.cells       = previousState ? this.fromState(previousState) : this.empty();
    this.over        = over ? over : false;
    this.won         = won ? won : false;
}

我使用此ScalaJS外观进行了映射:

@js.native
class Grid[T <: Tile](val size: Int,
                      val tileFactory: TileFactory[T],
                      previousState: js.Array[js.Array[TileSerialized]],
                      val over: Boolean,
                      val won: Boolean) extends js.Object {

  val cells: js.Array[js.Array[T]] = js.native

  def this(size: Int, tileFactory: TileFactory[T]) = this(???, ???, ???, ???, ???)

  ...

}

我想扩展Grid类,我这样做了:

@ScalaJSDefined
class ExtendedGrid(
                    override val size: Int,
                    override val tileFactory: TileFactory[Tile],
                    previousState: js.Array[js.Array[TileSerialized]],
                    override val over: Boolean,
                    override val won: Boolean) extends Grid(size, tileFactory, previousState, over, won) {

  ...

}

但是现在我还需要为这个ExtendedGrid类实现重载的构造函数。

问题是,我该怎么做?

理想情况下,我想做类似的事情:

def this(size: Int, tileFactory: TileFactory[Tile]) = super(size: Int, tileFactory: TileFactory[Tile])

但根据我的理解,这在Scala中是不可能的。

为了尝试一下,我试着简单地复制我在门面中定义的原始重载构造函数:

def this(size: Int, tileFactory: TileFactory[T]) = this(???, ???, ???, ???, ???)

编译但显然导致浏览器错误:

Uncaught scala.NotImplementedError: an implementation is missing

然后我尝试了:

def this(size: Int, tileFactory: TileFactory[Tile]) = this(size, tileFactory, this.empty(), false, false)

模仿原始JavaScript函数的行为,但无济于事。它产生了这个错误:

this can be used only in a class, object, or template

1 个答案:

答案 0 :(得分:3)

您尝试调用的构造函数不是真正重载。它更接近具有可选值的默认参数。在JS中,默认参数基本上是undefined。所以你可以用不同的方式建模父构造函数:

@js.native
class Grid[T <: Tile](val size: Int,
                      val tileFactory: TileFactory[T],
                      previousState: js.UndefOr[js.Array[js.Array[TileSerialized]]] = js.undefined,
                      _over: js.UndefOr[Boolean] = js.undefined,
                      _won: js.UndefOr[Boolean] = js.undefined) extends js.Object {
  val over: Boolean = js.native
  val won: Boolean = js.native
  val cells: js.Array[js.Array[T]] = js.native

  ...
}

然后你可以在定义你的类时模仿相同的结构:

@ScalaJSDefined
class ExtendedGrid(size: Int,
                   tileFactory: TileFactory[Tile],
                   previousState: js.UndefOr[js.Array[js.Array[TileSerialized]]] = js.undefined,
                   _over: js.UndefOr[Boolean] = js.undefined,
                   _won: js.UndefOr[Boolean] = js.undefined) extends Grid(size, tileFactory, previousState, _over, _won) {

  ...

}

顺便说一下,不要使用override val,因为您将值传递给父构造函数,并且从超类中获取val