In JavaScript, what are specific reasons why creating functions within a loop can be computationally wasteful?

前端 未结 2 1249
醉话见心
醉话见心 2021-01-13 22:36

In JavaScript, what are specific reasons why creating functions within a loop can be computationally wasteful?

On page 39 of JavaScript the Good Parts, Douglas Crock

2条回答
  •  难免孤独
    2021-01-13 23:01

    Because you're creating several Function objects instead of reusing just one.

    Example of creating an identical function...

    for (var i = 0; i < 10; i++) {
        // v--creating identical function in each iteration.
        (function(j) {
            var el = document.createElement('a');
            el.onclick = function() { alert(j); };
            document.body.appendChild(el);
        })(i);
    }
    

    Example of reusing a named function...

    for (var i = 0; i < 10; i++) {
        var el = document.createElement('a');
          // ----------v---calling a reusable function
        el.onclick = createHandler(i);
        document.body.appendChild(el);
    }
    
    function createHandler(j) {
        return function() { alert(j); };
    }
    

    The two examples have the same outcome, but the second doesn't require the overhead of making two functions during the loop. Instead it creates just the one handler.

提交回复
热议问题