gpt4 book ai didi

javascript - 如何使用 Kotlin 生成一个 javascript 函数 `constructor` ?

转载 作者:行者123 更新时间:2023-11-29 20:55:12 24 4
gpt4 key购买 nike

我想使用 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 函数?

最佳答案

顶层函数应该没有问题。 fun constructor() {} 应该可以正常工作,生成 function constructor(){}。至少在 Kotlin 1.2.31 中是这样。

另一方面,禁止使用名为 constructor 的成员函数(例如,您无法在输出 js 文件中获取 A.prototype.constructor = function () {})。一方面会破坏 - 检查实现。

修改类构造函数中的构造函数属性应该是可能的:

// 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);
}

希望对您有所帮助。

关于javascript - 如何使用 Kotlin 生成一个 javascript 函数 `constructor` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49632814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com