TL; DR是,当将Web worker的onmessage()处理程序定义为函数声明而不是函数表达式时,它不起作用。 (至少在Chrome中是这样。)我一生都无法想到原因。
我有以下简单的示例设置:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Web worker test</title>
<script src="index.js"></script>
</head>
<body>
<input type="button" value="test1" onclick="run('test1.js')">
<input type="button" value="test2" onclick="run('test2.js')">
</body>
</html>
index.js
function run(filename) {
worker = new Worker(filename);
worker.postMessage("test");
}
test1.js
onmessage = function(msg) {
console.log(msg.data);
}
console.log(self.onmessage);
test2.js
function onmessage(msg) {
console.log(msg.data);
}
console.log(self.onmessage);
您可以在http://mrbean.cryogenia.com/~davedude/webworkertest/自己尝试。如果单击test1按钮,它将记录以下内容(至少在Chrome 79.0.3945.117上):
ƒ (msg) {
console.log(msg.data);
}
test1.js:2 test
这表明函数已按预期定义,并且处理程序正在运行。
相反,当您单击test2时,您得到的只是这个:
ƒ onmessage(msg) {
console.log(msg.data);
}
这显示脚本is正常运行,并且已定义函数,无论出于何种原因,它都没有充当处理程序。
delete <fnName>
事先运行一样。这是另一个例子: <script>
Object.defineProperty(window, 'fn', {
set(newVal) {
console.log('setter invoked');
},
configurable: true
});
</script>
<script>
function fn() {
}
console.log(window.fn);
</script>