如何使用 Kotlin 生成一个 javascript 函数`constructor`?
How to use Kotlin to generate a javascript function `constructor`?
我想使用 Kotlin 生成一些 JavaScript 如下所示:
function MyComponent() {
self.constructor = function() {}
}
问题是 constructor
是 Kotlin 中的关键字,我不能像这样写:
class MyComponent {
fun constructor() {}
}
我也试过:
class MyComponent {
@JsName("constructor")
fun ctor() {}
}
它仍然报告如下错误:
JavaScript name generated for this declaration clashes
with built-in declaration {1}
如何生成名称为 constructor
的 javascript 函数?
top-level函数应该没有问题。 fun constructor() {}
应该可以正常工作,产生 function constructor(){}
。至少这是它在 Kotlin 1.2.31 中的作用。
另一方面,禁止使用名为 constructor
的成员函数(例如,您无法在输出 js 文件中获取 A.prototype.constructor = function () {}
)。一方面会破坏 is
-check 实现。
在 class 构造函数中修改构造函数 属性 应该是可能的:
// Kotlin
class A {
init{
this.asDynamic().constructor = fun(a: Int) { println(a) }
}
}
// JS
function A() {
this.constructor = A_init$lambda;
}
function A_init$lambda(a) {
println(a);
}
希望对您有所帮助。
我想使用 Kotlin 生成一些 JavaScript 如下所示:
function MyComponent() {
self.constructor = function() {}
}
问题是 constructor
是 Kotlin 中的关键字,我不能像这样写:
class MyComponent {
fun constructor() {}
}
我也试过:
class MyComponent {
@JsName("constructor")
fun ctor() {}
}
它仍然报告如下错误:
JavaScript name generated for this declaration clashes
with built-in declaration {1}
如何生成名称为 constructor
的 javascript 函数?
top-level函数应该没有问题。 fun constructor() {}
应该可以正常工作,产生 function constructor(){}
。至少这是它在 Kotlin 1.2.31 中的作用。
另一方面,禁止使用名为 constructor
的成员函数(例如,您无法在输出 js 文件中获取 A.prototype.constructor = function () {}
)。一方面会破坏 is
-check 实现。
在 class 构造函数中修改构造函数 属性 应该是可能的:
// Kotlin
class A {
init{
this.asDynamic().constructor = fun(a: Int) { println(a) }
}
}
// JS
function A() {
this.constructor = A_init$lambda;
}
function A_init$lambda(a) {
println(a);
}
希望对您有所帮助。