summaryrefslogtreecommitdiff
path: root/tests
diff options
context:
space:
mode:
authorDamien George <damien@micropython.org>2025-07-21 14:51:46 +1000
committerDamien George <damien@micropython.org>2025-07-24 14:38:08 +1000
commit45aa65b67d075fa8b2e71d57f1a94566f51207bb (patch)
tree61702ce933d5358c5e6957d6dedd19bcf764c3eb /tests
parent9b61bb93f9e34314a527375bd9803693f08a9a63 (diff)
webassembly/objjsproxy: Fix binding of self to JavaScript methods.
Fixes a bug in the binding of self/this to JavaScript methods. The new semantics match Pyodide's behaviour, at least for the included tests. Signed-off-by: Damien George <damien@micropython.org>
Diffstat (limited to 'tests')
-rw-r--r--tests/ports/webassembly/method_bind_behaviour.mjs43
-rw-r--r--tests/ports/webassembly/method_bind_behaviour.mjs.exp11
2 files changed, 54 insertions, 0 deletions
diff --git a/tests/ports/webassembly/method_bind_behaviour.mjs b/tests/ports/webassembly/method_bind_behaviour.mjs
new file mode 100644
index 000000000..24de0fa3b
--- /dev/null
+++ b/tests/ports/webassembly/method_bind_behaviour.mjs
@@ -0,0 +1,43 @@
+// Test how JavaScript binds self/this when methods are called from Python.
+
+const mp = await (await import(process.argv[2])).loadMicroPython();
+
+// Test accessing and calling JavaScript methods from Python.
+mp.runPython(`
+import js
+
+# Get the push method to call later on.
+push = js.Array.prototype.push
+
+# Create initial array.
+ar = js.Array(1, 2)
+js.console.log(ar)
+
+# Add an element using a method (should implicitly supply "ar" as context).
+print(ar.push(3))
+js.console.log(ar)
+
+# Add an element using prototype function, need to explicitly provide "ar" as context.
+print(push.call(ar, 4))
+js.console.log(ar)
+
+# Add an element using a method with call and explicit context.
+print(ar.push.call(ar, 5))
+js.console.log(ar)
+
+# Add an element using a different instances method with call and explicit context.
+print(js.Array().push.call(ar, 6))
+js.console.log(ar)
+`);
+
+// Test assigning Python functions to JavaScript objects, and using them like a method.
+mp.runPython(`
+import js
+
+a = js.Object()
+a.meth1 = lambda *x: print("meth1", x)
+a.meth1(1, 2)
+
+js.Object.prototype.meth2 = lambda *x: print("meth2", x)
+a.meth2(3, 4)
+`);
diff --git a/tests/ports/webassembly/method_bind_behaviour.mjs.exp b/tests/ports/webassembly/method_bind_behaviour.mjs.exp
new file mode 100644
index 000000000..ab3743f66
--- /dev/null
+++ b/tests/ports/webassembly/method_bind_behaviour.mjs.exp
@@ -0,0 +1,11 @@
+[ 1, 2 ]
+3
+[ 1, 2, 3 ]
+4
+[ 1, 2, 3, 4 ]
+5
+[ 1, 2, 3, 4, 5 ]
+6
+[ 1, 2, 3, 4, 5, 6 ]
+meth1 (1, 2)
+meth2 (3, 4)