This is a reading note from [JavaScript the good parts].
We know that you can use JavaScript's prototype feature to write extension modules for the original type. Use the following methods:
function (Name, func) { = func}
Add a handy extension method to all the objects in JavaScript. This convenient method saves us the manual input Object.prototype.xxxx each time
Now we're going to add an extension method to the string type called deentityify, which is shaped like < or &qout; Such a string is replaced by his original appearance.
Naturally, we need a table with a replacement rule:
var entity = { ' "', ' < ', ' > '}
But now the question is, where does this watch make him exist?
Scenario 1. There are global variables.
Scenario 2. There is deentityify in this function.
Scenario 1 is not feasible, because global variables are evil?? We should try to avoid using global variables.
Then try Solution 2:
String.method (' Deentityify ',function(){ varentity ={quot:‘"‘, lt:' < ', GT:' > ' } return This. replace (/&[^&;] +);/g,function(A, b) {varR =Entity[b]; return typeofr = = = ' String '?r:a; })})vars = "<">"s.deentityify ()//< ">
The result is correct, but there is a problem that when you call Deentityify, the entity is evaluated once, which obviously increases the overhead.
It seems that program 2 is not the most ideal, there is no way to evade it? Imagine that if you let the entity only value once, and then save his results, and then each time you call deentityify the result of the entity directly, instead of every call to go to evaluate him once again. Can this be done?
Of course, the answer is to use closures:
String.method (' Deentityify ',function(){ varentity ={quot:‘"‘, lt:' < ', GT:' > ' } return function () { return This. replace (/&[^&;] +);/g,function(A, b) {varR =Entity[b]; return typeofr = = = ' String '?r:a; }) }}())
Instead of returning results directly from Scenario 2, the scheme of closure is to return a function and then immediately evaluate the value of the result as a deentityify value.
It feels a bit around, but one of the benefits is that entity is evaluated here only in String.method (), and later, every time we use deentityify, we just work directly with the value of the entity, without having to evaluate it every time. This is the power of closures.
[JavaScript] using closures to write modules