You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
functionmyNew(context,...args){if(typeofcontext!=='function'){thrownewError('newOperator function the first param must be a function')}letobj=Object.create(context.prototype);// 原型链连接constres=context.apply(obj,args);if((typeofres==='object'&&res!==null)||typeofres==='function')returnres;returnobj;}
// 第一版,使用eval执行函数function_templ(str,data){letstring="var p = [];p.push('"+str.replace(/[\r\t\n]/g,"").replace(/<%=(.*?)%>/g,"');p.push($1);p.push('").replace(/<%/g,"');").replace(/%>/g,"p.push('")+"');"eval(string);returnp.join('');}
第二版
可以使用Function构造函数,达到一样的效果
functiontmpl(str,data){varstr=document.getElementById(str).innerHTML;varfn=newFunction("obj","var p = []; p.push('"+str.replace(/[\r\t\n]/g,"").replace(/<%=(.*?)%>/g,"');p.push($1);p.push('").replace(/<%/g,"');").replace(/%>/g,"p.push('")+"');return p.join('');");returnfn(data);};
不过值得注意的是:其实 tmpl 函数没有必要传入 data 参数,也没有必要在最后 return 的时候,传入 data 参数,即使你把这两个参数都去掉,代码还是可以正常执行的。
其他API
new
apply
call
bind
函数柯里化
函数组合
trim 消除先后空格
大数相加
拷贝
浅拷贝
深拷贝
模板引擎
手动实现tmplate的模板引擎
以下模板作为demo
将模板替换为字符串,然后执行这段字符串,通过eval/Function
<% 转化为
');
%>转化为
p.push('
<%=xxx%>转化为
');p.push(xxx);p.push('
第一版
第二版
可以使用
Function
构造函数,达到一样的效果不过值得注意的是:其实 tmpl 函数没有必要传入 data 参数,也没有必要在最后 return 的时候,传入 data 参数,即使你把这两个参数都去掉,代码还是可以正常执行的。
这是因为:
第三版
使用white 省略多余的属性值
第四版
如果我们使用的变量obj,发生了改变
这样子导致了每次实例化的时候都要重新的new Function
我们使tmpl返回一个函数,接受我们传递的变量
大数相加
The text was updated successfully, but these errors were encountered: