new Function

2019-11-09  本文已影响0人  静_summer

new Function

let fn = new Function('a', 'b', 'return a + b')
fn()
// 前面都是参数,后面是函数体

// 实现一个js模版引擎
// with 作用域 with(obj) {访问obj内的变量}\
// new Function () {} 返回一个函数
let str = `
   <%if(user){%>
       hello <%=user.name%>
   <%}else{%>
       hello world
   <%}%>
   <ul>
   <%for(let i = 0; i < total; i++) {%>
       <li><%=i%></li>
   <%}%>
   </ul>
`
let options = {user: {name: 'xxx'},  total: 5}
function render (str, options) {
   let head = 'let tpl = ``; \n with(obj) { \n tpl += `'
   str = str.replace(/<%=([\s\S]+?)%>/g, function() {
       return '${' + arguments[1] + '}'
   })
   str = str.replace(/<%([\s\S]+?)%>/g, function() {
       return '` \n' + arguments[1] + 'tpl+=`'
   })
   let tail = "`} \n return tpl;"
   let html = head + str + tail;
   let fn = new Function('obj', html)
   return fn(options);
   // console.log(fn(options));
}
render(str, options)
上一篇 下一篇

猜你喜欢

热点阅读