Why is this a closure?


T

Tom de Neef

When I run the code below through JSLint, the report says:
Global test
1 test()
Closure compare
....

I thought I had understood the concept of closure: to keep a function's
execution context alive by passing a reference to a local function. But
that's not what is done here. Can you explain pls or point me to some text
that will explain. The Google references I've checked seem to indicate that
this is not a closure, albeit there is one that says that any function
within a function will be a closure.
Tom

//code
function test(){
"use strict";
function compare(context,id){
return context==id;
}
function check(context,id){
return compare(context,id) || compare(context,id.toLowerCase());
}
check('dummy','DUMMY');
}
 
Ad

Advertisements

T

Tom de Neef

Jake Jarvis said:
<snip>

From JSLint's manual

http://www.jslint.com/lint.html#report

| Report
|
| If JSLint is able to complete its scan, it generates a function
| report. It lists for each function:
| ...
| /Closure/: The variables and parameters that are declared in the
| function that are used by its inner functions.

And is that then indeed what a closure is? I do not see how it binds local
variables or why it shows that "Closures are one of the most powerful
features of ECMAScript". To me the examplecound come straight from Algol 60,
which doesn't know about closures at all. That's why I am confused.
Tom
 
Ad

Advertisements

R

RobG

"Jake Jarvis" <[email protected]> schreef in bericht





And is that then indeed what a closure is?

For some, that is sufficient. But I think most javascript programmers
require a definition more like that in the FAQ: the closure needs to
persist beyond the life of the outer function, e.g.

var isJustDigits = (function() {
var re = /^\d+$/;
return function(n) {
return re.test(n);
}
}

where the function assigned to isJustDigits() retains a closure to the
variable re. It could also be said that even if there was no re
variable involved, the returned function has a closure to the
activation object of the outer function and the global object. But
those details are not usually considered a closure.

I do not see how it binds local
variables or why it shows that "Closures are one of the most powerful
features of ECMAScript".

They are, but your example is minimalist at best.
To me the examplecound come straight from Algol 60,
which doesn't know about closures at all. That's why I am confused.

And why for most a closure requires a bit more than scoping rules. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top