【问题标题】:Access the JS this from scala.js从 scala.js 访问 JS
【发布时间】:2015-04-30 03:40:02
【问题描述】:

我需要从 scala.js 调用一个类似的方法:

sigma.classes.graph.addMethod('getNodesCount', function() {
  return this.nodesArray.length;
});

这就是在JS中引入库来访问类sigma.classes.graph的内部数组nodesArray的方式。我尝试了类似的东西

trait GraphClassesJS extends js.Object {
  def addMethod(name:String,handler: js.Function0[Any]):Unit=js.native
}

我尝试用

打电话
s.classes.graph.addMethod("getNodesCount",()=>js.ThisFunction.nodesArray.length)

但我明白了

 value nodesArray is not a member of object scala.scalajs.js.ThisFunction
[error]     s.classes.graph.addMethod("getNodesCount",()=>js.ThisFunction.nodesArray.length)

我该怎么做? 谢谢 雷纳尔多

【问题讨论】:

    标签: scala.js


    【解决方案1】:

    您误解了js.ThisFunction 的性质。它不是来自 JS 的 this 的语法替代品。它是采用this 作为显式参数的函数的另一种类型层次结构。

    你需要的定义几乎就是你写的,但是将js.Function0替换为js.ThisFunction0,并指定包含nodesArray字段的Thing的类型(可能是Graph?):

    trait Thing extends js.Object {
      def nodesArray: js.Array[Node]
    }
    
    trait GraphClassesJS extends js.Object {
      def addMethod(name: String, handler: js.ThisFunction0[Thing, Any]): Unit = js.native
    }
    

    现在,你可以这样称呼它:

    s.classes.graph.addMethod("getNodesCount", thiz => thiz.nodesArray.length)
    

    现在thiz 完全等同于 JS this。其类型推断为Thing

    【讨论】:

    • 我更接近但还没有编译。我有:
    • @gilcu2 您的评论似乎比预期的要早。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多