Is there a way to use the "new" operator with arguments on a dynamic variable in Kotlin JavaScript?

For example: “new window.classNameK(a,b,c)” does not seem to have any representation in Kotlin. If there were no parameters, I could call it using js(“new window.classNameK()”, but since it does have parameters, I can’t call it.

I’ve been able to make functions in JavaScript and call them, but it is a very ugly solution.

I suppose I am just proposing this feature, due to it not being mentioned in the documentation or the specs.

https://kotlinlang.org/docs/reference/dynamic-type.html

fun newSomething(a: dynamic, b: dynamic, c: dynamic): dynamic{
     return js(“new window.classNameK(a,b,c)”)
}

will probably work.

Though it is probably a good idea to add constructors for dynamic into standard library.

And more generic version:

fun createInstance(type: dynamic, vararg args: dynamic): dynamic {
  val argsArray = (listOf(null) + args).toTypedArray()
  return js("new (Function.prototype.bind.apply(type, argsArray))")
}

can be called as:

createInstance(window.classNameK, a, b, c)

More safe version:

fun <T : Any> JsClass<T>.createInstance(vararg args: dynamic): T {
  @Suppress("UNUSED_VARIABLE")
  val ctor = this

  @Suppress("UNUSED_VARIABLE")
  val argsArray = (listOf(null) + args).toTypedArray()

  //language=JavaScript 1.6
  return js("new (Function.prototype.bind.apply(ctor, argsArray))").unsafeCast<T>()
}

Can be used as

window.classNameK.jsClass.createInstance(a, b, c)

(jsClass is property from std lib)

1 Like

What about named parameters?