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:
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: