the keyword self
is used to approach the Worker’s API, which means that no matter the scope (even if its a closure) you will get access to the Worker's API (I'm not sure if you can redeclare self
to something else and loose the Worker's API reference, but I believe it is protected by JS so you don't be able to override it).
And the following lines:
self.addEventListener('message', function(e) {
self.postMessage(e.data);
}, false);
Are simply adding an event listener for the 'message'
event, which will send the data from the event back to the reference of the webworker in the context where it was spawned (most commonly the current browsers thread, or a parent worker). And we can quote what the false
boolean determines:
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
If true, the listener will receive synthetic events
dispatched by web content (the default is false for chrome and true
for regular web pages). This parameter is only available in Gecko and
is mainly useful for the code in add-ons and the browser itself. See
Interaction between privileged and non-privileged pages for an
example.
From: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
A more technical description of the keyword 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.
Quoted from: https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/self
window
object. – Fugeself
butpostMessage
directly. Not sure if there's a practical difference. MDN Example: developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/… – Dextran