开发者

Closures for Event Handlers - is "return" a must

开发者 https://www.devze.com 2023-02-11 11:19 出处:网络
I can implement event handlers in javascript in two ways as mentioned below, I would like to know if there any difference between the two styles or in both the cases click_handler is a closure and the

I can implement event handlers in javascript in two ways as mentioned below, I would like to know if there any difference between the two styles or in both the cases click_handler is a closure and there is no difference. I am having the confusion because I read somewhere that closures are formed only then "r开发者_运维百科eturn" 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);


Closure is formed when the 2 functions are created. They functionally should work the same in terms of "closure forming". You don't need a return for a closure to be formed.

However...

In #1, when you call foo(), you will then add an event listener to onClick. If you call it again and again and again, it'll keep attaching to the onClick event...

In #2, when you call foo(), you're simply "re-closuring" the function. If you call it over and over again, it won't re-attach itself to the onClick event...

And, in #1, if someElement's reference has been updated since, when calling foo() again, it'll use the new someElement's reference...

Assuming you just want to attach the onClick function once, and you won't have to re-attach it anymore, I'll write the code like this...

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

This self-executing function will eliminate the need to add "foo" in to the global, since you only use it once.


Just to explicitly kill your confusion:

Closures and the return statement has nothing to do with each other and they do not affect each others behavior in any way.

Closures are not objects like numbers, string or functions. You can never assign a closure to a variable for example. And you can't return closures. What you return in your second example is (strictly speaking) a function (not a closure) that has "closed" over the variable a (and hence created a closure). Closures are something that exist alongside your functions, but you never operate directly on them. You can work with the functions containing them or you can alter their state (through the variables they close over), but the closure itself is a more abstract thing.

EDIT: I do realize that the terms closure and function are often used in place of each other. It's easy to mix it up since there is a 1-1 relation between the two in JavaScript. This of course only adds to the confusion :)

0

精彩评论

暂无评论...
验证码 换一张
取 消