How does #onmessage and #postmessage work to communicate between main thread and HTML5's webworkers?
<p>I"m learning about HTML5 workers from <a href="http://www.htmlgoodies.com/html5/tutorials/introducing-html-5-web-workers-bringing-multi-threading-to-javascript.html#fbid=x3SFEKTHrLf" rel="nofollow">here</a> and the author uses <code>self.onmessage</code> and <code>self.postmessage</code> to communicate between the main thread and the worker "because the worker cannot access the DOM." But in the below it seems like <code>self</code> is referring to both the main thread and the worker.</p>

<pre><code>function CalculatePi(loop)
{
    var c = parseInt(loop);
    var f = parseFloat(loop);
    var n=1;

    //these errors will need more work…
    if (isNaN(c) || f != c ) {
      throw("errInvalidNumber");
    } else if (c&lt;=0) {
      throw("errNegativeNumber");
    }

    for (var i=0,Pi=0;i&lt;=c;i++) {
      Pi=Pi+(4/n)-(4/(n+2));
      n=n+4;
    }
    self.postMessage({'PiValue': Pi});
}
//wait for the start 'CalculatePi' message
//e is the event and e.data contains the JSON object
self.onmessage = function(e) {
  CalculatePi(e.data.value);
}
</code></pre>

<p>The above code is from a separate js file containing the worker, and I understand that the <code>self</code> in <code>self.onmessage</code> is referring to the worker receiving a message from the main thread to start calculating, but why would it use <code>self.postMessage</code> to post a message back to itself? Is the default receipt(s) of #postMessage and #onmessage include both the main thread and worker?</p>

<p>Later on, the author posts the calucation of pi through this function:</p>

<pre><code>worker.onmessage = function(e) {
  document.getElementById("PiValue").innerHTML = e.data.PiValue;
};
</code></pre>

<p>How does this work when the worker isn't suppose to have access to the DOM? It clearly is using document.getElementById here.</p>