search

Home  >  Q&A  >  body text

Should one avoid declaring functions within functions (except for intentional closures)?

$('.dom').on('click', function () {
    function test() {
        console.log('abc');
    } 
});

The function test is declared every time it is clicked, and then the click callback is executed and GCed. If the dom is clicked more than once, then each click callback has one more function declaration. I remember that function declarations are not allowed in the jshint specification. Isn't the current situation similar when writing to a loop? So what is the best way to deal with it? Should I move the declaration position of the test function to the outside? This will cause closure and the test function cannot be recycled. If the user only uses this logic once, it will obviously be a loss. What should I do? trade off? ~

迷茫迷茫2778 days ago578

reply all(3)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-19 10:25:40

    There is a difference between a loop and a function.

    The loop is not an independent scope, so declaring the function in it will be declared in advance, but not in the function. jshint prevents duplicate definitions.

    function a() {
        function b() {
        }
    }

    b will only be declared when function a is executed, and if there is no external reference pointing to b, it will be destroyed after the function executes the next round of recycling.

    In fact there is not much difference.

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-19 10:25:40

    function test(message) {
      console.log(message);
    }
    
    $('.dom').on('click', function () {
      test('abc')
    });

    Test is thrown away after use, it will not be irrecyclable.

    reply
    0
  • 为情所困

    为情所困2017-05-19 10:25:40

    If it is executed only once, it can be like this:

    var elem = $('.dom'); 
    elem.on('click', (function() {
        return function foo(e) {
            // do something...
            elem.off('click', foo);
        };
    }()));

    The defined foo will not affect the outside world, uninstall it immediately after use and wait for recycling.
    Clean, hiding the merit and fame

    reply
    0
  • Cancelreply