Есть ли способ избежать eval в этом блоке JavaScript? - PullRequest
0 голосов
/ 07 января 2011

Есть ли способ избежать eval в этом блоке js?

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

Ответы [ 3 ]

3 голосов
/ 07 января 2011

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 голос
/ 07 января 2011

Как насчет

if (typeof window[r] == "undefined")
0 голосов
/ 07 января 2011
 while (r = requires.pop()) {
  if (typeof window[r] == "undefined") alert(r + ' is required');
 }
...