问题是console.log()在执行时没有显示对象的真实状态。进一步的挖掘发现事实上
Module
还没准备好。
我引用:
https://kripken.github.io/emscripten-site/docs/getting_started/FAQ.html
如何判断页面何时已完全加载并且调用已编译函数是安全的?
在页面完全加载之前调用编译的函数会导致
在错误中,如果函数依赖于可能不存在的文件
[…]
另一种选择是定义
onRuntimeInitialized函数:
Module['onRuntimeInitialized'] = function() { ... };
当运行时准备好并可以调用编译后的代码时,将调用该方法。
调整我的
test.js
(工作)文件修复了此问题:
self.Module = {
locateFile: function (s) {
console.log(s);
return s;
}
// Add this function
onRuntimeInitialized: function() {
test();
}
};
self.importScripts("main.js");
// note: `main.js` is the JavaScript glue file created by emcc
self.data = {};
// to pass data from the main JS file
self.onmessage = function(messageEvent) {
console.log(messageEvent); // works!
self.data = messageEvent; // save the data
}
// gets executed when everything is ready.
self.test = function() {
// we may safely use self.data and self.Module now!
console.log(self.Module.ccall("test")); // works!
}