Constructing JS Objects

The PyScript (Pyodide) and PyScript(Micropython) version of this recipe are identical,

Python lacks the new operator that JavaScript uses to construct new objects. To work around this, proxies of JavaScript classes within Python gain a new() which calls their constructor.

If you have a JavaScript class defined like so:

var Boat = class Boat{
    constructor(size, power){
        this.size = size
        this.power = power
    }
}

We can construct new instances of the class within Python like so:

from js import Boat

sailboat = Boat.new("33ft", "sailpower")
tugboat = Boat.new("80ft", "diesel")

print(f"{sailboat.size=}, {tugboat.power=}")

This also works for classes already defined in the JavaScript global scope. For example, to create a new JavaScript Float64Array (an array of 8-byte floats), you can use the following similar syntax:

from js import Float64Array

my_array = Float64Array.new([1,2,3,4])

print(my_array)
print(f"{my_array.byteLength= }")