JavaScript new Keyword in Go


JavaScript new keyword are used very often. For example, Date(), XMLHttpRequest(), or WebSocket() need to be newed before being used. We will use Date() as example and show you how to write equivalent code in Go/GopherJS.

JavaScript

To print the date info in JavaScript, you can do the following with new keyword:

var d = new Date();
console.log(d);

You can try the code online in w3schools. [1]

GopherJS

The above code in Go/GopherJS is as follows:

import (
      "github.com/gopherjs/gopherjs/js"
)

d := js.Global.Get("Date").New()
println(d)

You can try the code online:

Run Code on GopherJS Playground

GopherJS + godom

To make your code more readable, we can prettify the above code with godom:

import (
      . "github.com/siongui/godom"
)

d := Window.Get("Date").New()
println(d)

For more exaples for JavaScript new keyword in Go, see [2], [3], [4].

Chain Dots

From the comment of @pbrown12303, if you have to new the following chain dots in JavaScript:

var x = new joint.dia.Graph;

The following code in Go/GopherJS will not work:

x := js.Global.Get("joint.dia.Graph").New()

The correct syntax in Go/GopherJS is:

x := js.Global.Get("joint").Get("dia").Get("Graph").New()

References:

[1]JavaScript Dates
[2]GopherJS XMLHttpRequest (XHR) and MakeFunc Example
[3][GopherJS] WebSocket Client Example With Echo Server
[4][Golang] Access HTTP Request Header by XHR getAllResponseHeaders()