Skip to content

Comment on Closures for class/module privacy considered harmfulparent

Comments

But if they're really closures, how can we explain such behaviour?:

http://jsfiddle.net/9uqZg/

Because you aren't really showing the pattern that is being discussed. In that example, the two incr variables are in the same lexical scope, and you are calling your closure in that same scope. So when your inner function calls incr, it calls the first one it sees, moving outwards through nested scopes. Later, when you overwrite incr, the new one gets called. You've really effectively only closed over the variable x with respect to the lexical scope that incr is in.

Here's four variations that hopefully show the difference.

http://jsfiddle.net/7ZfvP/1/

edit: bad link

Indeed, you're right. It still feels quite strange to me to use the fact that a function (used as behaviour and not data) is, from the language features, technically a variable to call that kind of construct a closure. But thanks for the effort and occasion to think about it.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.