Closing for event handlers is a "return"

I can implement event handlers in javascript in two ways, as indicated below, I would like to know if there is a difference between the two styles or in both cases click_handler is closing and there is no difference. I got confused because I read somewhere that closures are formed only when the “return” is used with an anonymous function

function foo() {
    var a = 5;

    function click_handler() {
        a++;
    }
    someElement.addEventHandler('click', click_handler, false);
}

OR

function foo() {
    var a = 5;

    return function() {
        a++;
    }
}

click_handler = foo()
someElement.addEventListener('click', click_handler, false);
+3
source share
2 answers

A closure is formed when two functions are created. They should functionally function the same in terms of “closure”. You do not need a refund to close.

However...

# 1, foo(), onClick. , onClick...

# 2, foo(), " " . , onClick...

# 1, someElement , foo() someElement...

, onClick , , , ...

(function() {
  var a = 0;
  someElement.addEventListener("click", function() {
    a++;
  }, false);
})();

"foo" , .

+2

, :

return , .

- , , . , . . , , ( ) ( ), "" a (, , ). - , , . , , ( , ), .

EDIT: , . , 1-1 JavaScript. , , :)

+1

Source: https://habr.com/ru/post/1792815/


All Articles