- (function(){})(this,function(){}
- + - ! function($) (), function 前
- $(function(){})与 (function(){})(
- + - ! function($) (), function 前
- js function/Function
- cost function and loss function
- jquery(function(){})与(function()
- js中(function(){}()),(function(){
- jQuery(function(){ })与(function(
- jQuery(function(){})和$(function(
Function 对象(类)
Function是所有JS函数的构造函数,也可用于生成一个新的函数
函数名本质就是一个变量名, 是指向某个 Function 实例的引用
function a(){}
a instanceof Function//true
使用方法
new Function([arg1, arg2, ..., argN,] function_body)
Function
与eval
最大的不同是其使用的变量不会从其实例化时上下文中读取,而总是从全局变量中读取。可以认为通过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)
网友评论