如何从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

最佳答案

您可以使用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

关于scala.js - 如何从Scala.js调用Javascript apply()?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25380753/

10-13 05:47