我需要一個簡單的js引擎。 所以,我創建了一個功能:JS如何將對象設置爲eval作爲內容?
function compile(tpl, scope){
return tpl.replace(/\{\{([\s\S]+?)\}\}/g, function(caught, content){
var compiled;
try{
compiled = eval.call(scope, content);
}catch(e){
compiled = caught;
console.error(e);
}finally{
return compiled;
}
});
}
好,調用它。
compile('<div>{{ maxSize/1024/1024 }}M</div>', { maxSize: 1048576 });
但是,錯誤跳出「MAXSIZE沒有定義」。
我該如何解決它?
不能傳遞一個對象作爲變量範圍。 'eval'將採用它的封閉範圍。 – 2014-09-02 10:44:38
這可能會有幫助:http://perfectionkills.com/global-eval-what-are-the-options/ – Sarfraz 2014-09-02 10:47:43