Web worker中的全局变量 [英] Global variable in Web worker
问题描述
我正在使用这个Web工作者,其中声明了一个全局变量。我可以在新生成的Web worker(worker 2)中访问相同的(worker 1中的全局变量)吗?
I am using this Web worker which has a Global variable declared in it. Can I access the same (Global variable in worker 1) in the newly spawned web worker(worker 2)?
当我尝试在web worker中使用jQuery时,我收到错误窗口未定义。有没有办法在 Web Worker
中使用jQuery?
When I've tried using jQuery in web worker, I get error "window is not defined". Is there any way to use jQuery in a Web Worker
?
importScripts('jquery-latest.js');
function fetch_ajax(url) {
$.ajax({
type: 'GET',
url: url,
success: function(response) {
postMessage(response);
}
});
}
fetch_ajax('test.txt');
推荐答案
网络工作者没有窗口
object。
Web Workers don't have a window
object.
要访问全局状态,请使用 self
代替将同时适用于主要状态的代码线程和工作线程。
To access global state, use self
instead, code that will work on both the main thread and the worker thread.
但请注意,您仍然无法访问或操作父 DOM
(例如,通过 self.jQuery
获取 window.jQuery
)。
But note that you still won't be able to access or manipulate the parent DOM
(e.g. get window.jQuery
via self.jQuery
).
当主线程窗口 self
指向Window对象时,在工作线程中 self
指向一个单独的 WorkerGlobalScope
对象。
While the main thread window self
points to the Window object, in worker threads self
points to a separate WorkerGlobalScope
object.
这篇关于Web worker中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!