On page 90 of Crockford's JavaScript: The Good Parts, he has code has the following:
String.method('entityify', function(){
var character = {
'<': '<',
'>': '>',
'&': '&',
'"': '"'
};
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 = {
'<': '<',
'>': '>',
'&': '&',
'"': '"'
};
return this.replace(/[<>&"]/g, function(c){
return character[c];
});
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With