ruanyf / es6tutorial

《ECMAScript 6入门》是一本开源的 JavaScript 语言教程,全面介绍 ECMAScript 6 新增的语法特性。
http://es6.ruanyifeng.com/
Other
21.23k stars 8.95k forks source link

es6模板编译eval问题 #555

Closed dajunJS closed 6 years ago

dajunJS commented 6 years ago

`function compile(template){ const evalExpr = /<%=(.+?)%>/g; const expr = /<%([\s\S]+?)%>/g;

template = template .replace(evalExpr, '); \n echo( $1 ); \n echo(') .replace(expr, '); \n $1 \n echo(');

template = 'echo(' + template + ');';

let script = `(function parse(data){ let output = "";

function echo(html){
  output += html;
}

${ template }

return output;

})`;

return script; } let parse = eval(compile(template)); div.innerHTML = parse({ supplies: [ "broom", "mop", "cleaner" ] });` 阮老师,网上很多说eval最好不要用,会有安全或性能问题.请问有没有其它替换方案

ruanyf commented 6 years ago

自己用 eval 问题不大的,只要不处理用户输入的数据即可。