Skip to content

Commit cc83b78

Browse files
author
Romain Doumenc
committed
Cherry pick issue golang#56084
1 parent 6885bad commit cc83b78

File tree

4 files changed

+24
-0
lines changed

4 files changed

+24
-0
lines changed

misc/wasm/wasm_exec.js

+1
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@
9696
constructor() {
9797
this.argv = ["js"];
9898
this.env = {};
99+
this.scope = globalThis;
99100
this.exit = (code) => {
100101
if (code !== 0) {
101102
console.warn("exit code:", code);

misc/wasm/wasm_exec_node.js

+1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ const go = new Go();
2424
go.argv = process.argv.slice(2);
2525
go.env = Object.assign({ TMPDIR: require("os").tmpdir() }, process.env);
2626
go.exit = process.exit;
27+
go.scope = {};
2728
WebAssembly.instantiate(fs.readFileSync(process.argv[2]), go.importObject).then((result) => {
2829
process.on("exit", (code) => { // Node.js exits if no event handler is pending
2930
if (code === 0 && !go.exited) {

src/syscall/js/js.go

+6
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,12 @@ func Global() Value {
135135
return valueGlobal
136136
}
137137

138+
// Scope returns the Javascript object attached to the scope field of the Go class.
139+
// If nothing has been explicitly set, behaves like [js.Global].
140+
func Scope() Value {
141+
return jsGo.Get("scope")
142+
}
143+
138144
// ValueOf returns x as a JavaScript value:
139145
//
140146
// | Go | JavaScript |

src/syscall/js/js_test.go

+16
Original file line numberDiff line numberDiff line change
@@ -688,3 +688,19 @@ func TestGlobal(t *testing.T) {
688688
t.Errorf("got %#v, want %#v", got, js.Global())
689689
}
690690
}
691+
692+
func TestScope(t *testing.T) {
693+
ident := js.FuncOf(func(this js.Value, args []js.Value) any {
694+
return args[0]
695+
})
696+
defer ident.Release()
697+
698+
js.Scope().Set("key", "value")
699+
if js.Scope().Get("key").String() != "value" {
700+
t.Errorf("get key %s: got %#v", "key", js.Scope().Get("key"))
701+
}
702+
703+
if got := ident.Invoke(js.Scope()); got.Equal(js.Global()) {
704+
t.Errorf("scope %#v mixed with global %#v", got, js.Global())
705+
}
706+
}

0 commit comments

Comments
 (0)