Skip to content

Commit ef681aa

Browse files
committed
Introduce Scope for JS (#56084)
1 parent 2d097e3 commit ef681aa

File tree

4 files changed

+24
-0
lines changed

4 files changed

+24
-0
lines changed

lib/wasm/wasm_exec.js

+1
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@
104104
constructor() {
105105
this.argv = ["js"];
106106
this.env = {};
107+
this.scope = globalThis;
107108
this.exit = (code) => {
108109
if (code !== 0) {
109110
console.warn("exit code:", code);

lib/wasm/wasm_exec_node.js

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

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
@@ -733,3 +733,19 @@ func TestGlobal(t *testing.T) {
733733
t.Errorf("got %#v, want %#v", got, js.Global())
734734
}
735735
}
736+
737+
func TestScope(t *testing.T) {
738+
ident := js.FuncOf(func(this js.Value, args []js.Value) any {
739+
return args[0]
740+
})
741+
defer ident.Release()
742+
743+
js.Scope().Set("key", "value")
744+
if js.Scope().Get("key").String() != "value" {
745+
t.Errorf("get key %s: got %#v", "key", js.Scope().Get("key"))
746+
}
747+
748+
if got := ident.Invoke(js.Scope()); got.Equal(js.Global()) {
749+
t.Errorf("scope %#v mixed with global %#v", got, js.Global())
750+
}
751+
}

0 commit comments

Comments
 (0)