4 ms·
Slight quibble: his JS example is a bit contrived. He gives the following: js> a = 5; 5 js> f = function(x) { return x+a }; function (x){retur
by benaiah 13y ago
Slight quibble: his JS example is a bit contrived. He gives the following:
js> a = 5;
5
js> f = function(x) { return x+a };
function (x){return x+a}
js> f(10)
15
js> a = 100
100
js> f(10)
110
Well, yes, this is true, but it's not a problem with JS' closures, it's a problem with its variable declaration. a is declared as a global variable by default. Yes, this is bad, and everyone knows it's bad, but it's a bit orthogonal to closures. It's very simple to solve this in JS:
js> a = 5;
5
js> f = function (x) { var a = 5; return x + a };
function(x){var a;return x+a}
js> f(10)
15
js> a = 100
100
js> f(10)
15
- Adrock 13y agoI'm quibbling with a quibble, but I don't agree that it's orthogonal to closures. Your example doesn't really demonstrate the eponymous "closing" aspect of the closure and doesn't solve the problem that the OP is calling out. Closures are functions that refer to non-local variables. [1] [2] Whether the language provides lexical or dynamic scoping [3] is critical to how and when closures can be used in that language. [1] http://en.wikipedia.org/wiki/Closure_(computer_science) http://en.wikipedia.org/wiki/Closure_(computer_science) [2] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guid... [3] http://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping_and_dynamic_scoping http://en.wikipedia.org/wiki/Scope_(computer_science)#Lexica...