WebWorkers中的'self'关键字是什么意思

What does the 'self' keyword mean in WebWorkers

我不明白第 7、8、9 行:

var worker = new Worker('doWork.js');

worker.addEventListener('message', function(e) {
  console.log('Worker said: ', e.data);   // Here it send's the data.
}, false);

worker.postMessage('Hello World'); // Send data to our worker.



 //7 self.addEventListener('message', function(e) {
   //8   self.postMessage(e.data);
   //9 }, false);

这段代码在做什么? 1.what 代码行在第 7 行触发消息事件? 2.what数据是在第8行的postMessage中传递的? 3.what自己在这做吗?

关键字 self 用于接近 Worker 的 API,这意味着无论范围如何(即使它是闭包),您都可以访问 Worker 的 API (我不确定您是否可以将 self 重新声明为其他内容并释放 Worker 的 API 引用,但我相信它受 JS 保护,因此您无法覆盖它)。

以及以下几行:

self.addEventListener('message', function(e) {
    self.postMessage(e.data);
}, false);

只是为 'message' 事件添加事件侦听器,它将事件中的数据发送回其生成上下文中的 webworker 引用(最常见的是当前浏览器线程,或 parent 工人)。我们可以引用 false 布尔值确定的内容:

useCapture Optional If true, useCapture indicates that the user wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. Events which are bubbling upward through the tree will not trigger a listener designated to use capture. See DOM Level 3 Events and JavaScript Event order for a detailed explanation. If not specified, useCapture defaults to false.

Note: For event listeners attached to the event target; the event is in the target phase, rather than capturing and bubbling phases. Events in the target phase will trigger all listeners on an element regardless of the useCapture parameter.

Note: useCapture became optional only in more recent versions of the major browsers; for example, it was not optional prior to Firefox 6. You should provide this parameter for broadest compatibility.

wantsUntrusted如果为true,监听器将接收合成事件 由 Web 内容调度(chrome 的默认值为 false,为 true 对于常规网页)。此参数仅适用于 Gecko 和 主要对 add-ons 中的代码和浏览器本身有用。看 特权页面和 non-privileged 页面之间的交互 例如。

发件人:https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

关键字的更技术性描述 self:

The self read-only property of the WorkerGlobalScope interface returns a reference to the WorkerGlobalScope itself. Most of the time it is a specific scope like DedicatedWorkerGlobalScope, SharedWorkerGlobalScope, or ServiceWorkerGlobalScope.

引自:https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/self