liveBook · Manning

Namespace

As explained in Learn Go with Pocket-Sized Projects

A JavaScript namespace is a named scope or object used to organize and expose JavaScript-accessible functions and values.

A namespace is a named JavaScript scope or object for organizing functions exposed by Go WebAssembly. Registering on js.Global() makes a function available everywhere; assigning it to a specific object keeps the API narrower. section 12.2.2

Choose the exposure scope according to application size:

  • Use the global namespace for a small application, calling generate(). section 12.2.2
  • Create a JavaScript object for a specific namespace, expose it as multiplyApp, and call multiplyApp.generate(). section 12.2.2

Expose a function under a namespace

multiply := js.Global().Get("Object").New()\nmultiply.Set("generate", js.FuncOf(m.generate))\njs.Global().Set("multiplyApp", multiply)\n\nThe browser can then invoke multiplyApp.generate(). section 12.2.2

Listing 12.12 main.go : Exposing a function in a specific namespace
multiply := js.Global().Get("Object").New() #1
multiply.Set("generate", js.FuncOf(m.generate)) #2
js.Global().Set("multiplyApp", multiply) #3

Inspect the complete object-creation and function-registration pattern. section 12.2.2

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Shows function registration, object creation, property assignment, and browser invocation.
Examples
Uses a multiplication exercise with generate() globally or multiplyApp.generate() under a named object.
What you can do after
Apply it via Go's js API to expose a function globally or under a named JavaScript object.
How it connects
Connects namespaces with JavaScript objects, global scope, WebAssembly, and DOM interaction.

Also explained in

Compare how 20 books explain namespace →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.