I'm trying to use GopherJS, but I couldn't find documentation about how to use it.
Here's the Go code:
package main
import (
"github.com/gopherjs/gopherjs/js"
)
func main() {
t := js.Global.Get("key").Int()
println(t)
js.Global.Set("keySet", 4)
}
Then I convert it to JS using GopherJS and paste it:
JS code:
var key = 3
// Pasted GopherJS Code
"use strict";
(function() {
...
}).call(this);
// End GopherJS Code
console.log(keySet)
It prints:
0
4
Why? It should've printed
3
4
Here's what I've tried (changing the Go code and re-converting):
func main() {
t := js.Global.Get("key").Float()
println(t)
js.Global.Set("keySet", 4)
}
prints
NaN
4
func main() {
t := js.Global.Get("key").Int64()
println(t)
js.Global.Set("keySet", 4)
}
prints
typ { '$high': 0, '$low': 0, '$val': [Circular] }
4
What am I doing wrong?
js.Global
does not do what you seem to think it does.
The js.Global
variable is documented as:
Global gives JavaScript's global object ("window" for browsers and "GLOBAL" for Node.js).
This means that:
js.Global.Get("key")
is accessing window.key
in the browser, or GLOBAL.key
in Node.js, not a global variable key
, as you're trying to do.
More generally, if you want standard JS to access GopherJS-generated code you should use the js.Wrap
method as documented.