无法从 WebWorker 内部访问某些函数和变量
Cannot access some functions and variables from inside a WebWorker
我在从我创建的 Web Worker 中的 main 调用函数时遇到问题。我用 Java 语言创建了一个类似于枚举的对象:
const states = {
START: 'start',
ADDCHAR: 'addchar',
WORDBEFORE: 'wordbefore',
REMOVECHAR: 'removechar',
RESET: 'reset'
}
并且每个元素都有一个我在以下代码中使用的状态:
self.addEventListener('message', function(e) {
while( true ){
switch ( state ){
case states.START:
start();
state = states.ADDCHAR;
case states.ADDCHAR:
addchar();
state = states.WORDBEFORE;
case states.WORDBEFORE:
sleep(3000);
state = states.REMOVECHAR;
case states.REMOVECHAR:
removeChar();
state = states.RESET;
case states.RESET:
reset();
state = states.START;
}
sleep(1000);
}
});
问题是我无法从 main 访问函数:start()
、addchar()
等
如何从 Web Worker 内部访问这些功能?我从 main 向 web worker 发送消息,但是从 web worker 到 main 执行 'connection' 是行不通的(而且仍然发送消息并不能解决我所有的问题,因为我必须从switch 语句中的 main )。
我尝试对代码进行多次修改,但无法解决问题。
浏览器中加载的 JavaScript 脚本范围内的函数和全局变量 window 网络工作者无法访问。
您可以使用 importScripts
将它们导入您的工作人员。
Worker threads have access to a global function, importScripts(), which lets them import scripts. It accepts zero or more URIs as parameters to resources to import; all of the following examples are valid:
importScripts(); /* imports nothing */
importScripts('foo.js'); /* imports just "foo.js" */
importScripts('foo.js', 'bar.js'); /* imports two scripts */
importScripts('//example.com/hello.js'); /* You can import scripts from other origins */
我在从我创建的 Web Worker 中的 main 调用函数时遇到问题。我用 Java 语言创建了一个类似于枚举的对象:
const states = {
START: 'start',
ADDCHAR: 'addchar',
WORDBEFORE: 'wordbefore',
REMOVECHAR: 'removechar',
RESET: 'reset'
}
并且每个元素都有一个我在以下代码中使用的状态:
self.addEventListener('message', function(e) {
while( true ){
switch ( state ){
case states.START:
start();
state = states.ADDCHAR;
case states.ADDCHAR:
addchar();
state = states.WORDBEFORE;
case states.WORDBEFORE:
sleep(3000);
state = states.REMOVECHAR;
case states.REMOVECHAR:
removeChar();
state = states.RESET;
case states.RESET:
reset();
state = states.START;
}
sleep(1000);
}
});
问题是我无法从 main 访问函数:start()
、addchar()
等
如何从 Web Worker 内部访问这些功能?我从 main 向 web worker 发送消息,但是从 web worker 到 main 执行 'connection' 是行不通的(而且仍然发送消息并不能解决我所有的问题,因为我必须从switch 语句中的 main )。
我尝试对代码进行多次修改,但无法解决问题。
浏览器中加载的 JavaScript 脚本范围内的函数和全局变量 window 网络工作者无法访问。
您可以使用 importScripts
将它们导入您的工作人员。
Worker threads have access to a global function, importScripts(), which lets them import scripts. It accepts zero or more URIs as parameters to resources to import; all of the following examples are valid:
importScripts(); /* imports nothing */
importScripts('foo.js'); /* imports just "foo.js" */
importScripts('foo.js', 'bar.js'); /* imports two scripts */
importScripts('//example.com/hello.js'); /* You can import scripts from other origins */