Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crockford's entityify method -why the closure?

Tags:

javascript

On page 90 of Crockford's JavaScript: The Good Parts, he has code has the following:

String.method('entityify', function(){

  var character = {
    '<': '&lt;',
    '>': '&gt;',
    '&': '&amp;',
    '"': '&quot;'
  };

  return function(){
    return this.replace(/[<>&"]/g, function(c){
      return character[c];
    });
  };
}());

console.log("<&>".entityify());

Is there a good reason for the closure and immediately invoked outer function? The following seems to work just as well:

String.method('entityify', function(){

  var character = {
    '<': '&lt;',
    '>': '&gt;',
    '&': '&amp;',
    '"': '&quot;'
  };

  return this.replace(/[<>&"]/g, function(c){
    return character[c];
  });
});
like image 360
mr_c Avatar asked Jul 24 '15 15:07

mr_c


1 Answers

By doing it the way he did, he creates the character object once and reuses it. With your edit, you recreate it every time. You could argue it either way, but that's the difference. His uses fractionally more memory. Yours takes fractionally longer per call (maybe, depends on whether creating the object takes longer than the extra scope traversal step his has; it probably does, though). In neither case is it likely to be anything that you'd notice in the real world.

like image 158
T.J. Crowder Avatar answered Oct 19 '22 05:10

T.J. Crowder