简体   繁体   English

有没有一种方法可以避免在此JavaScript代码块中进行评估?

[英]Is there a way to avoid eval in this block of JavaScript?

Is there a way to avoid eval in this block of js? 有没有一种方法可以避免在此js块中进行评估?

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

The eval here is completely pointless: 这里的eval完全没有意义:

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

This will do the exact same thing, also note that r leaks into the global scope. 这将做完全相同的事情,还要注意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');
       }
   }
} ());

怎么样

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM