var str = ‘Hello <%= name %>!‘;
var o = {
name: ‘Alice‘
};
function tmpl(str, obj) {
str = ‘var p = [];‘ +
‘with (obj) {p.push(‘ + parser(str) + ‘)};‘ +
‘return p;‘
var r = (new Function(‘obj‘, str))(obj);
return r.join(‘‘);
}
tmpl(str, o)
推测parser应该是返回"hello" ,"Alice","!"
代码就变成:
var str = ‘Hello <%= name %>!‘;
var o = {
name: ‘Alice‘
};
function tmpl(str, obj) {
str = ‘var p = [];‘ +
‘with (obj) {p.push("hello" ,"Alice","!")};‘ +
‘return p;‘
var r = (new Function(‘obj‘, str))(obj);
return r.join(‘‘);
}
tmpl(str, o)
核心部分就是:
var o = {
name: ‘Alice‘
};
var p = [];
with (o) {
p.push(‘Hello ‘, name, ‘!‘);
};
p.join(‘‘)
时间: 2024-10-25 00:44:35