SoFunction
Updated on 2025-04-14

A brief analysis of the source code of Prototype, supplement to the String part (IV)


function Template(template, pattern){
= template;
= pattern || /(^|.|\r|\n)(#\{(.*?)\})/;
}
= (function(){
function evaluate(obj){
return (this,function(match){
if(obj == null){
return match[0] + '';
}
var before = match[1] || '';
if(before == '\\'){
return match[2];
}
var ctx = obj;
var expr = match[3];
var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
match = (expr);
if (match == null){
return before;
}
while (match != null) {
var comp = match[1].search(/^\[/) != -1 ? match[2].replace(/\\\\]/g, ']') : match[1];
ctx = ctx[comp];
if (null == ctx || '' == match[3]) break;
expr = ('[' == match[3] ? match[1].length : match[0].length);
match = (expr);
}
return before + (ctx === null ? '' : String(ctx));
});
}
function gsub(replacement){
var pattern = ;
var result = '';
var match = null;
var source = ;
if (!( || )) {
replacement = replacement('');
return replacement + ('').join(replacement) + replacement;
}
while ( > 0) {
if (match = (pattern)) {
result += (0, );
result += replacement(match) === null ? '' : String(replacement(match));
source = ( + match[0].length);
}else {
result += source;
source = '';
}
}
return result;
}
return {
constructor : Template,
evaluate : evaluate
}
})();