Deriving from an external class that is implemented using the Javascript class syntax yields browser error "TypeError: class constructors must be invoked with |new|"


#1

(I tried to file an issue but apparently a new account doesn’t have permission.)

Foo.js:

class Foo {
    hello() {
        console.log("Hello from Foo!")
    }
}

Foo.kt:

external open class Foo {
    open fun hello()
}

Bar.kt:

class Bar : Foo() {
    override fun hello() {
        println("Hello from Bar!")
    }
}

fun main() {
    Foo().hello()
    Bar().hello()
}

Result (Firefox):

TypeError: class constructors must be invoked with |new|

This is fixed by replacing Foo.js with:

function Foo() {
}

Foo.prototype.hello = function() {
    console.log("Hello from Foo!")
}

(I’d like to attach a file here but seems not supported or no permission.) https://www.sendspace.com/file/injzec


#2

The generated code that causes the error is

function Bar() {
    Foo.call(this)
}

The apparent fix is to generate this instead:

function Bar() {
    if (Foo.prototype.hasOwnProperty('constructor')) {
        Foo.constructor.call(this)
    } else {
        Foo.call(this)
    }
}

Well, the user may have manually created a function named ‘constructor’. Perhaps there is a foolproof way to check whether Foo was defined with the class syntax.


#3

Thank you for reporting this. Kotlin/JS indeed can’t currently extends JS classes. One of the workarounds would be to transpile classes down to ES5.

One normally does have permissions to create a new issue at https://kotl.in/issue when they log in with their JetBrains account. Are you logged in as guest? Could you elaborate on problems you have so I can forward it to admin people?


#4

Upon pressing the “Create” button, there’s an error in the lower-right corner saying “Please select a project”. I don’t see a way to select a project, but a tag may be selected (if this is the same thing then the terminology needs to be fixed). However the only kotlin-related tags are

KotlinDSL
KotlinConf
kotlin c interop
kotlin-dsl
kotlin-grammar
kotlinx-metadata-jvm

none of which appear to be a main kotlin project.

Could the problem be that I made an account at the youtrack site, then logged in here using that account? If the reverse order would have worked then, well, someone who just wants to report an issue wouldn’t know that.