如何从Scala.js调用Javascript apply()?

时间:2014-08-19 10:08:48

标签: scala.js

如何从Scala.js代码调用Javascript对象上定义的名为apply()的函数?

显而易见的解决方案不起作用,因为apply始终被Scala.JS(?)编译到其父对象的函数调用中:

var test = {
  apply: function(idx) {...},
  apple: function(idx) {...}
}
trait Test extends js.Object {
  def apple(idx: Int) : Int = ???
  def apply(idx: Int) : Int = ???
}

val test = js.Dynamic.global.test.asInstanceOf[Test]

test.apple(1) // works, of course

test.apply(1) // does not work (seems to be compiled into the call test(1) ?)

js.Dynamic.global.test.apply(1) // does not work either

1 个答案:

答案 0 :(得分:5)

您可以使用apply在外观类型中注释@JSName("apply")方法。这将产生所需的行为:

trait Test extends js.Object {
  def apple(idx: Int) : Int = ???
  @JSName("apply")
  def apply(idx: Int) : Int = ???
}

测试:

val test = js.Dynamic.literal(
    apply = (idx: Int) => idx,
    apple = (idx: Int) => idx
).asInstanceOf[Test]

test.apple(1) // -> 1
test.apply(1) // -> 1

对于动态类型的情况,您必须手动调用applyDynamicNamed

val dyn = test.asInstanceOf[js.Dynamic]

dyn.applyDynamicNamed("apply")(1) // -> 1