Typically, JavaScript code runs either on Node.js or in the browser. Any code that runs on Node.js should have access to what is known as Node.js global objects (https://nodejs.org/api/globals.html). If your code ends up running on a Node.js environment, GopherJS gives you access to the global objects using the js.Global variable, which returns a *js.Object that hosts your global variables. You can then access a specific object using a method called Get, then call the object methods using a method called Call. Let's see an example to better explain this paragraph.
Run the following code:
package main
import (
"github.com/gopherjs/gopherjs/js"
)
func main() {
//the console variable is of type *js.Object
console := js.Global.Get("console")
/*
the *js.Object support a method called Call which can access the methods of console.
*/
console.Call("log", "Hello world!!")
}
This will be the equivalent of writing a piece of Node.js JavaScript code that looks like this:
console.log("Hello World!!");
The js.Global object opens up very interesting possibilities, as it allows you to access Node.js modules and use them in your Go code. For example, let's assume we imported a Node.js module called prettyjson to our node project, and we would like to use it in our Go code. prettyjson is a real package, it has a method called render(), which converts objects to beautiful-looking JSON. This is shown in the following code:
package main
import (
"fmt"
"github.com/gopherjs/gopherjs/js"
)
func main() {
//Some data type
type MyType struct {
Name string
Projects []string
}
//A value from our data type
value := MyType{Name: "mina", Projects: []string{"GopherJS", "ReactJS"}}
/*
Call the prettyjson module, this is equivalent to the following code in JavaScript:
var prettyjson = require("prettyjson");
*/
prettyjson := js.Global.Call("require", "prettyjson")
// The line below is equivalent to 'prettyjson.render(value);' in JavaScript
result := prettyjson.Call("render", value)
/*
Do something with result
*/
}
As mentioned, JavaScript code can also run on a browser. The globals available to the browser are different. For example, the following piece of code will run fine on a browser, but won't be happy if you try to run it with Node.js:
package main
import (
"github.com/gopherjs/gopherjs/js"
)
func main() {
document := js.Global.Get("document")
document.Call("write", "Hello world!!")
}
That is because "document" is a global object available for almost all browsers.
In the next section, we will take a look at the GopherJS commands.