Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js/wasm: introduce scope for JS object #72786

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/wasm/wasm_exec.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@
constructor() {
this.argv = ["js"];
this.env = {};
this.scope = globalThis;
this.exit = (code) => {
if (code !== 0) {
console.warn("exit code:", code);
Expand Down
1 change: 1 addition & 0 deletions lib/wasm/wasm_exec_node.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ require("./wasm_exec");
const go = new Go();
go.argv = process.argv.slice(2);
go.env = Object.assign({ TMPDIR: require("os").tmpdir() }, process.env);
go.scope = {};
go.exit = process.exit;
WebAssembly.instantiate(fs.readFileSync(process.argv[2]), go.importObject).then((result) => {
process.on("exit", (code) => { // Node.js exits if no event handler is pending
Expand Down
6 changes: 6 additions & 0 deletions src/syscall/js/js.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,12 @@ func Global() Value {
return valueGlobal
}

// Scope returns the Javascript object attached to the scope field of the Go class.
// If nothing has been explicitly set, behaves like [js.Global].
func Scope() Value {
return jsGo.Get("scope")
}

// ValueOf returns x as a JavaScript value:
//
// | Go | JavaScript |
Expand Down
16 changes: 16 additions & 0 deletions src/syscall/js/js_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -733,3 +733,19 @@ func TestGlobal(t *testing.T) {
t.Errorf("got %#v, want %#v", got, js.Global())
}
}

func TestScope(t *testing.T) {
ident := js.FuncOf(func(this js.Value, args []js.Value) any {
return args[0]
})
defer ident.Release()

js.Scope().Set("key", "value")
if js.Scope().Get("key").String() != "value" {
t.Errorf("get key %s: got %#v", "key", js.Scope().Get("key"))
}

if got := ident.Invoke(js.Scope()); got.Equal(js.Global()) {
t.Errorf("scope %#v mixed with global %#v", got, js.Global())
}
}