Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/469.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript:在其他函数中评估函数_Javascript_Function_Eval - Fatal编程技术网

JavaScript:在其他函数中评估函数

JavaScript:在其他函数中评估函数,javascript,function,eval,Javascript,Function,Eval,我有一个图像尺寸计算函数,它在执行时返回缩放的图像尺寸值。(注意:图像列表及其尺寸可从阵列中访问。) 然后我有一些HTML中的按钮: <a id="button1"></a> <a id="button2"></a> <a id="button3"></a> 这些按钮调整我需要应用维度计算的数组中的当前图像索引。但是:我不想在所有按钮单击函数中复制和粘贴相同的setDesiredDimensions函数,而只是将其作为更清

我有一个图像尺寸计算函数,它在执行时返回缩放的图像尺寸值。(注意:图像列表及其尺寸可从阵列中访问。)

然后我有一些HTML中的按钮:

<a id="button1"></a>
<a id="button2"></a>
<a id="button3"></a>
这些按钮调整我需要应用维度计算的数组中的当前图像索引。但是:我不想在所有按钮单击函数中复制和粘贴相同的setDesiredDimensions函数,而只是将其作为更清晰代码的快捷方式进行访问/评估


我听到了eval();它既危险又缓慢。有什么想法吗?

如果您在所有事件处理程序都可以访问的范围内定义了
设置了DesiredDimensions
,则可以调用该函数。这就是函数的用途

我认为您的问题在于函数使用的是全局变量,而不是传递给它的参数。在您的示例中,您将
imagesOrigWidths[currindex]
作为参数传递,但也在函数内部访问
imagesOrigWidths[currindex]
,这没有意义

重新定义它,这样您就可以简单地传递它需要的参数,比如

function setDesiredDimensions(orig_width, orig_height, limit) {
    var width = Math.min(orig_width, limit);
    var height = Math.ceil((width / orig_height) * orig_height);

    // some more calculation code here...

    return {width:width,height:height};
}    

Eval是邪恶的。不要用它。曾经。为什么不直接调用
setDesiredDimensions()
?Eval通常被认为是一个坏主意-请看,您可以避免
Eval
的危险一面,但不能避免缓慢。您似乎可以再次调用该函数?看起来你根本不需要评估?
$('#button1').click( function() {
     currindex = (currindex+1) % max;

     **I need to evaluate setDesiredDimensions function here **

     $("#imageswap").attr({src: imgSrcBase(imagesGuids[currindex]), width: size.width, height: size.height})
});
function setDesiredDimensions(orig_width, orig_height, limit) {
    var width = Math.min(orig_width, limit);
    var height = Math.ceil((width / orig_height) * orig_height);

    // some more calculation code here...

    return {width:width,height:height};
}