Why is this a closure?

Discussion in 'Javascript' started by Tom de Neef, Feb 12, 2012.

  1. Tom de Neef

    Tom de Neef Guest

    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.

    function test(){
    "use strict";
    function compare(context,id){
    return context==id;
    function check(context,id){
    return compare(context,id) || compare(context,id.toLowerCase());
    Tom de Neef, Feb 12, 2012
    1. Advertisements

  2. Tom de Neef

    Tom de Neef Guest

    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 de Neef, Feb 12, 2012
    1. Advertisements

  3. Tom de Neef

    RobG Guest

    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.

    They are, but your example is minimalist at best.
    And why for most a closure requires a bit more than scoping rules. :)
    RobG, Feb 13, 2012
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.