Yoe*_*cia 4 javascript scala scala.js
我正在将一个JavaScript库移植到Scalajs.JS对象是在JavaScript端使用new关键字创建的,所以这就是我在大多数情况下所做的.
trait Point extends js.Object {
def normalize(length: Double): Point = js.native
}
Run Code Online (Sandbox Code Playgroud)
这似乎适用于方法,但是,这对构造函数不起作用.
@JSName("paper.Point")
object PointNative extends js.Object {
def apply(props: RectProps): Rectangle = js.native
}
Run Code Online (Sandbox Code Playgroud)
上面的代码不起作用.它传递类型检查和编译,但在运行时它返回undefined.
如果我像这样修改了PointNative那么一切都很好.
import js.Dynamic.{ global => g, newInstance => jsnew }
object PointNative {
def apply(props: RectProps): Rectangle = jsnew(g.paper.Point)(props).asInstanceOf[Point]
}
Run Code Online (Sandbox Code Playgroud)
有没有办法将@JSName和js.native与new关键字一起使用?
谢谢!
由于在JavaScript API中paper.Point需要使用new关键字进行实例化,因此需要将PointNative定义为类:
@JSName("paper.Point")
class PointNative(props: PointProps) extends js.Object {
...
}
Run Code Online (Sandbox Code Playgroud)
允许用它实例化它
new PointNative(props)
Run Code Online (Sandbox Code Playgroud)
就像你在JavaScript中所做的那样.
如果您还希望能够仅使用它来实例化它
PointNative(props)
Run Code Online (Sandbox Code Playgroud)
那么你需要js.Object用一个apply()方法定义一个额外的非伴侣:
object PointNative {
def apply(props: PointProps): PointNative = new PointNative(props)
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果您需要伴侣PointNative作为a js.Object(因为您还想要定义其中的静态方法paper.Point),那么您可以apply()使用隐式类对其进行pimp :
implicit class PointNativeCompanionOps(val self: PointNative.type) extends AnyVal {
def apply(props: PointProps): PointNative = new PointNative(props)
}
Run Code Online (Sandbox Code Playgroud)