title: Crockford's deentityify method - p.41 of The Good Parts
body: <p>In a fit of self-improvement, I'm reading (and rereading) TGP by Señor Crockford. I cannot, however, understand the middlemost part of his deentityify method.</p>
  
  <pre><code>...
  return this.replace(...,
      function (a, b) {
         var r = ...
      }
  );
  </code></pre>
  
  <p>I think I understand that:</p>
  
  <ol>
  <li>this.replace is passed two arguments, the regex as the search value and the function to generate the replacement value;</li>
  <li>the b is used to access the properties in the entity object;</li>
  <li>the return <code>? r : a;</code> bit determines whether to return the text as is or the value of the appropriate property in entity.</li>
  </ol>
  
  <p>What I don't get at all is how the a &amp; b are provided as arguments into <code>function (a, b)</code>. What is calling this function? (I know the whole thing is self-executing, but that doesn't really clear it up for me. I guess I'm asking how is this function being called?)</p>
  
  <p>If someone was interested in giving a blow by blow analysis akin to <a href="https://stackoverflow.com/questions/2947749/line-by-line-explanation-of-javascript-good-parts-example">this</a>, I'd really appreciate it, and I suspect others might too.</p>
  
  <p>Here's the code for convenience:</p>
  
  <pre><code>String.method('deentityify', function ( ) {
      var entity = {
          quot: '"',
          lt: '&lt;',
          gt: '&gt;'
      };
  
      return function () {
          return this.replace(
              /&amp;([^&amp;;]+);/g,
              function (a, b) {
                  var r = entity[b];
                  return typeof r === 'string' ? r : a;
              }
          );
      };
  }()); 
  </code></pre>