Should one avoid declaring functions within functions (except for intentional closures)?
迷茫
迷茫 2017-05-19 10:23:40
0
3
543
$('.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? ~

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(3)
过去多啦不再A梦

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.

世界只因有你
function test(message) {
  console.log(message);
}

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

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

为情所困

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template