Javascript Web worker 中的全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11219775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:59:05  来源:igfitidea点击:

Global variable in Web worker

javascriptweb-worker

提问by Nigilan

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 工作者,其中声明了一个全局变量。我可以在新生成的 web worker(worker 2)中访问相同的(worker 1 中的全局变量)吗?

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?

当我尝试在 Web Worker 中使用 jQuery 时,出现错误“未定义窗口”。有没有办法在 jQuery 中使用 jQuery Web Worker

importScripts('jquery-latest.js');

function fetch_ajax(url) {
  $.ajax({
    type: 'GET', 
    url: url,
    success: function(response) {
    postMessage(response);  


    }
  });
}

fetch_ajax('test.txt');

回答by buley

Web Workers don't have a windowobject.

Web Workers 没有window对象。

To access global state, use selfinstead, code that will work on both the main thread and the worker thread.

要访问全局状态,请改用self同时在主线程和工作线程上工作的代码。

But note that you still won't be able to access or manipulate the parent DOM(e.g. get window.jQueryvia self.jQuery).

但请注意,您仍然无法访问或操作父级DOM(例如 get window.jQueryvia self.jQuery)。

While the main thread window selfpoints to the Window object, in worker threads selfpoints to a separate WorkerGlobalScopeobject.

而主线程窗口self指向Window对象,而在工作线程中self指向一个单独的WorkerGlobalScope对象。

回答by Felipe

Based on @buley tip, I did it:

根据@buley 提示,我做到了:

var window = self;

importScripts(/* dependencies here */);

/* my code */

In my case I was trying to use the ES6-Promise lib: https://github.com/jakearchibald/es6-promise#readme

就我而言,我试图使用 ES6-Promise 库:https: //github.com/jakearchibald/es6-promise#readme