3

JavaScript new Keyword in Go

 2 years ago
source link: http://siongui.github.io/2017/12/08/js-new-keyword-in-go/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK