web-worker JS 中 window[funcName]() 的等价物是什么?

What equivalant to window[funcName]() in web-worker JS?

我们如何在 web-worker JS 中编写 window[funcName]()

如何访问在脚本的顶级上下文中声明的函数?

WebWorker 中,您可以使用 self 来引用全局范围(您也可以使用 this (当它指向全局范围时,就像它适用于window):

// worker.js
function foo() {
  console.log("hello worker");
}

self['foo']()

您无法访问 window 对象,这实际上是 web-workers

的目标

The worker thread can perform tasks without interfering with the user interface

引用文档将回答您的问题:

workers run in another global context that is different from the current window. Thus, using the window shortcut to get the current global scope (instead of self) within a Worker will return an error.

但是您有包含一些内置功能的 self 对象。