Javascript Module Pattern Introduced In TGP Deentityify Method - Why Is This Pattern Necessary?
Crockford introduces a pattern in the deentityify method to create a module. He claims: The module pattern takes advantage of function scope and close to create relationships tha
Solution 1:
The basic reason for this pattern is to avoid re-evaluating entity
on every call. Replace entity
with something that is expensive to construct and doesn't change from call to call:
String.prototype.deentityify = function() {
// expensiveFunctionCall is called *once* - when the function is defined.
var entity = expensiveFunctionCall();
return function() {
return this.replace(/&([^&;]+);/g, function(a, b) {
var r = entity[b];
return typeof r === 'string' ? r : a;
}); //close function(a,b)
}; //close the returned function
}();
vs
String.prototype.deentityify = function() {
// expensiveFunctionCall is called
// *every time* "anyString".deentityify() is called.
var entity = expensiveFunctionCall();
return this.replace(/&([^&;]+);/g, function(a, b) {
var r = entity[b];
return typeof r === 'string' ? r : a;
}); //close function(a,b)
};
Post a Comment for "Javascript Module Pattern Introduced In TGP Deentityify Method - Why Is This Pattern Necessary?"