I have experience in Go but am totally green when it comes to Javascript. I've started playing around with Go's js/wasm target. I was wondering whether it's possible to define a JS class within golang. The syscall/js package provides no direct way to do so, but according to a tutorial, a JS class is essentially just a constructor function and a prototype. So I attempted to build the Rectangle toy example from the tutorial in Go:
package main
import (
"syscall/js"
)
// Attempt to create a simple javascript class:
//
// class Rectangle {
// constructor(height, width) {
// this.height = height;
// this.width = width;
// }
//
// // Method
// area() {
// return this.height * this.width;
// }
// }
func rectangleArea(this js.Value, args []js.Value) interface{} {
height := this.Get("height").Float()
width := this.Get("width").Float()
return height * width
}
func rectangleConstructor(this js.Value, args []js.Value) interface{} {
this.Set("height", args[0])
this.Set("width", args[1])
return this
}
func main() {
const name = "Rectangle"
rectangle := js.FuncOf(rectangleConstructor)
rectangle.Set("prototype", map[string]interface{}{
"constructor": rectangle,
"area": js.FuncOf(rectangleArea),
})
js.Global().Set(name, rectangle)
select {}
}
It seems to work in my browser's Javascript console: I can instantiate a Rectangle, extend the class, and so on. Cool. The one thing that worries me is that direct comparison between my Rectangle class and an identical Rectangle2 class defined in the JS console yields differences:
> Rectangle
function _makeFuncWrapper()
length: 0
name: ""
prototype: Object { constructor: _makeFuncWrapper(), area: _makeFuncWrapper() }
area: function _makeFuncWrapper()
constructor: function _makeFuncWrapper()
<prototype>: Object { … }
<prototype>: function ()
> Rectangle2
class Rectangle2 { constructor(height, width) }
length: 2
name: "Rectangle2"
prototype: Object { … }
area: function area()
constructor: class Rectangle2 { constructor(height, width) }
<prototype>: Object { … }
<prototype>: function ()
Of course, the differences might all be due to special Go/wasm magic.
Long story short, my question is: Is what I'm doing a sound and sane way to define JS classes from within Go? If not, is there a better way?