rustwasm / wasm-bindgen

Facilitating high-level interactions between Wasm modules and JavaScript
https://rustwasm.github.io/docs/wasm-bindgen/
Apache License 2.0
7.84k stars 1.08k forks source link

Fixed imports with late binding and `this` #4225

Closed RunDevelopment closed 2 weeks ago

RunDevelopment commented 1 month ago

Fixes #4214

The problem in #4214 was that function like document.write can't be imported as a function reference into WASM directly, because document.write does not capture the this argument (here document). Or in other words, there is a difference between:

export function __wbg_reload_90d82b22b83c1d99(text) {
    document.write(text); // `write` has `document` as the `this` arg
};

and

// there is no `this` arg, so `write` will fail when invoked in WASM
export const __wbg_reload_90d82b22b83c1d99 = typeof document.write === "function" ? document.write(text) : notDefined('document.write');

However, aside from this not being captured, the (let's called it) direct import style also didn't support late binding. If the object or function is only defined after the WASM module is instantiated, then the direct import style will cause an error.

This PR fixes both issues by always generating a wrapper function for imported function from global scope.

RunDevelopment commented 2 weeks ago

Added changelog.