EVAL dangerous 如何更换

EVAL dangerous How to replace it

我有以下用于弹出窗口的代码 window(客户端请求)。它使用 eval,我知道这很危险。有没有办法重写下面的脚本,使其不使用 (eval)?

/* exported popup_default , popup_help , popup_sitemap , popup_footerlinks */

var matchClass = ['popup_default', 'popup_sitemap', 'popup_footerlinks', 'popup_help'];
var newwindow = ''

var popup_default = 'width=800,height=640,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=250,top=200';
var popup_help = 'width=700,height=650,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=100,top=100';
var popup_sitemap = 'width=1000,height=600,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=100,top=100';
var popup_footerlinks = 'width=800,height=500,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=250,top=200';

function pop_ups() {
  "use strict";
  var x = 0;
  var popClass;
  while (x < matchClass.length) {
    popClass = "'." + matchClass[x] + "'";
    $(eval(popClass)).click(function() {
      var popurl = $(this).attr('href');
      var popupSpecs = $(this).attr('class');
      var popupName = Math.floor(Math.random() * 10000001);
      newwindow = window.open(popurl, popupName, eval(popupSpecs));
      return false;
    });
    x++;
  }
}

$(function() {
  "use strict";
  pop_ups();
});

你会想要使用

"use strict";
function makePopup(className, specs) {
    $('.'+className).click(function(e) {
        e.preventDefault();
        var popupName = Math.floor(Math.random()*10000001);
        window.open(this.href, popupName, specs);
    });
}
var popups = {
    popup_default:     'width=800,height=640,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=250,top=200',
    popup_help:        'width=700,height=650,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=100,top=100',
    popup_sitemap:    'width=1000,height=600,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=100,top=100',
    popup_footerlinks: 'width=800,height=500,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=250,top=200'
};
$(function() {
    for (var key in popups)
        makePopup(key, popups[key]);
});

而不是第一个 eval,只需使用字符串连接。而不是第二个 eval,使用对象查找 属性 名称。

感谢@Bergi

我更新了脚本的最后一部分,因为它抛出了一个错误:"The body of a for in should be wrapped in an if statement"

$(function() {
    "use strict";
    for (var key in popups) {
        if(popups.hasOwnProperty(key))
        {
           makePopup(key, popups[key]);
        }
    }
});

再次感谢您的帮助