Function

2021-04-29  本文已影响0人  李霖弢

Function 对象(类)

Function是所有JS函数的构造函数,也可用于生成一个新的函数
函数名本质就是一个变量名, 是指向某个 Function 实例的引用

function a(){}
a instanceof Function//true

使用方法

new Function([arg1, arg2, ..., argN,] function_body)

Functioneval最大的不同是其使用的变量不会从其实例化时上下文中读取,而总是从全局变量中读取。可以认为通过new Function生成的函数总是在全局上下文中被定义

  var a = { age: 20 }, b = "outer";
  function factory(a) {
    var b = "inner";
    return new Function(`
    console.log(${a}.age,b)
  `)
  }
  factory("{age:18}")();//18 "outer"

应用

// 实现一个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)
上一篇下一篇

猜你喜欢

热点阅读