2013-03-15 68 views
0

我不能得到這個編譯:導出函數內返回一個新的立即excecuted功能

export function Parse(jsonData) { 
     try { 
      if (jsonData.d != undefined) { 
       if (jsonData.d != "") { 
        return (new function("return " + jsonData.d))(); 
       } 
      } 
      else { 
       if (jsonData != "") { 
        return (new function("return " + jsonData))(); 
       } 
      } 
      return {}; 
     } 
     catch (e) { 
      return { exception: e.Message }; 
     } 
    } 

它既有(「迴歸」聲明說)下一個標記錯誤或}預期

回答

2

整體而言,JavaScript中最好避免使用new關鍵字。您可以創建立即執行的匿名功能,沒有它,就像這樣:

function Parse(jsonData) { 
    try { 
     if (typeof jsonData.d !== 'undefined') { 
      if (jsonData.d != "") { 
        return (function(j) { 
         return "return " + j.d; 
        }(jsonData)); 
       } 
      } else { 
       if (jsonData != "") { 
        return (function(j) { 
         return "return " + j; 
        }(jsonData)); 
       } 
      } 
      return {}; 
     } 
     catch (e) { 
      return { exception: e.Message }; 
     } 
} 

var data = { d: 'x' }; // 'test'; 
var result = Parse(data); 
alert(result); 

在這個例子中,我已經刪除了new關鍵字,通過jsonData到立即執行功能,並增加了return只是這樣我就可以測試結果。

+0

很酷的解決方案! – FutuToad 2013-03-18 09:17:25

0

你想要new Function,而不是new function,在這兩個地方(與JavaScript中相同)。