I don't understand the 7,8,9 line:
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);
What is doing this block of code? 1.what code line fires the message event in line 7? 2.what data is passed in the postMessage on line 8? 3.what does self do here?
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 redeclareself
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:
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 thefalse
boolean determines:From: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
A more technical description of the keyword
self
:Quoted from: https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/self