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();
returnfunction() {
returnthis.replace(/&([^&;]+);/g, function(a, b) {
var r = entity[b];
returntypeof 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();
returnthis.replace(/&([^&;]+);/g, function(a, b) {
var r = entity[b];
returntypeof 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?"