有没有办法在这个JavaScript块中避免使用eval?

时间:2011-01-07 17:44:22

标签: javascript eval

有没有办法在这块js中避免使用eval?

// Check requirements Prototype and Scriptaculous
(function () {
 var requires = [
  'Prototype'
  , 'Scriptaculous'
 ]
 while (r = requires.pop()) {
  if (eval('typeof ' + r + ' == "undefined"')) alert(r + ' is required');
 }
} ());

3 个答案:

答案 0 :(得分:3)

eval这里完全没有意义:

// since everything in the global scope gets defined on 'window'
typeof window[r] === 'undefined'; 

这将执行完全相同的操作,同时请注意r泄漏到全局范围。

// Check requirements Prototype and Scriptaculous
(function () {
    var requires = ['Prototype', 'Scriptaculous'];

   var r = ''; // make sure to __not__ override a global r
   while (r = requires.pop()) {
       if (typeof window[r] === 'undefined') {
           alert(r + ' is required');
       }
   }
} ());

答案 1 :(得分:1)

怎么样

if (typeof window[r] == "undefined")

答案 2 :(得分:0)

 while (r = requires.pop()) {
  if (typeof window[r] == "undefined") alert(r + ' is required');
 }