微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有这个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

解决方法:

您尝试调用的构造函数并未真正过载.它更接近具有带有可选值的认参数.在JS中,认参数基本上是未定义的.因此,您可以对父构造函数进行不同的建模:

@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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐