jQuery循环中嵌套函数的效率

时间:2012-12-30 22:08:03

标签: javascript jquery loops

在计算机资源方面更有效率。将事件处理程序放在循环中,如下所示:

$('ul li').each(function()
{
    $(this).mouseover(function()
    {
        // code to do something 
    });

或者让循环外部的函数在循环内部创建一个调用,如下所示:

$('ul li').each(function()
{
    $(this).mouseover(function()
    {
        doStuff($(this)); 
    });

function doStuff(liElem)
{
    // code to do something 
}

在我看来,第二个选项在计算机上会更容易,因为每次循环迭代时都不会重复执行某些操作的代码。每次循环时是否在计算机的内存中创建了事件处理程序的代码,还是只创建了一次?有什么想法吗?

1 个答案:

答案 0 :(得分:1)

可以进行各种优化,但要特定于您要求的方法, 请在下面的代码中找到答案作为内联评论

第一种方法:

$('ul li').each(function()
{
    // Maybe you might like to declare some variables here
    $(this).mouseover(function()
    {
        // code to do something

        // Maybe you might like to use the variables declared in above function

        // Disadvantage over other approach
        // The code written here will need to store the context information of the outer function and global context

        // Advantage over other approach
        // You can directly access the variables declared in the above function
    });
}

或者让循环外部的函数在循环内部创建一个调用,如下所示:

第二种方法:

$('ul li').each(function()
{
    // Maybe you might like to declare some variables here
    $(this).mouseover(function()
    {
        doStuff($(this)); 
    });
});

function doStuff(liElem)
{
    // code to do something

    // Advantage over other approach
    // The code written here will need to store the context information only for the global context

    // Disadvantage over other approach
    // You cannot directly access the variables declared in the outer function as you can in the other approach,
    // you will need to pass them to the doStuff function to access here
}