2012-04-19 124 views
1

我继承了一个JavaScript代码库,我是JavaScript新手。所以我使用JSHint来避免常见错误,误用。如何避免这种邪恶eval的情况?

JSHint发现这段代码,但我不知道如何避免邪恶的eval:

function GetProperties(object) { 
    var result, property, t; 
    result = ''; 
    for (property in object) { 
     if (property.indexOf('Get', 0) === 0) { 
      t = object[property] + "..."; 
      eval("if (GetNumOfParameter(t) == 0) var m = object." + property + "(); else var m = -100;"); 

      if (window.m != -100) { 
       result += property + ': ' + window.m + '\r\n'; 
      } 
     } 
    } 
    return result; 
} 
+3

'var m = object [property]()'也许? – 2012-04-19 14:28:41

回答

2

使用下,它是更好的,你不需要使用m如果你不”不要在其他地方使用它。

function GetProperties(object) { 
    var result, property, t; 
    result = ''; 
    for (property in object) { 
     if (property.indexOf('Get', 0) === 0) { 
      t = object[property] + "..."; 

      if (GetNumOfParameter(t) == 0) 
       result += property + ': ' + object[property]() + '\r\n'; 
     } 
    } 
    return result; 
} 
+0

而不是(例如)'GetNumOfParameter(t)== 0',你可以简单地'!GetNumOfParameter(t)' – Zirak 2012-11-26 13:58:23

相关问题