2014-09-02 94 views
1

我需要一個簡單的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沒有定義」

我該如何解決它?

+1

不能傳遞一個對象作爲變量範圍。 'eval'將採用它的封閉範圍。 – 2014-09-02 10:44:38

+0

這可能會有幫助:http://perfectionkills.com/global-eval-what-are-the-options/ – Sarfraz 2014-09-02 10:47:43

回答

2

什麼可以幫助可能是用另一種邪惡的建設with,做這樣的事情:

try { 
    compiled = (new Function('with(this){return ' + content + '}')).call(scope); 
} catch (...) 

這將使您的工作方式,但不會使之安全。

DEMO:http://jsfiddle.net/4rujz5b7/

+0

使用'with'的好主意。 – 2014-09-02 10:54:14

+0

謝謝,但我在嚴格模式 – phuxuth 2014-09-02 11:40:20

+1

@gordomium:那又怎麼樣?編譯的函數不是。 – Bergi 2014-09-02 11:42:21