Hacker News new | past | comments | ask | show | jobs | submit login

I don't see how that's refuting my point -- of course they don't share "y" because they're two completely different y's in two completely different local scopes.

I had understood your comment to mean that closures don't share variables, and I was just explaining that they certainly can. Maybe I'd misinterpreted what you were trying to say...




I wasn't trying to say that at all.

I was saying that two functions side by side have distinct closures, no matter how many variables they share.

The reason I said that was to point out that variables closed over by one function shouldn't affect which variables are closed over by nearby functions.

Actually I think I see how to make the wording clearer in the original. Brb.


My $0.02 regarding terminology that may help this discussion: what you call a scope is, in Lisp terms, a (lexical) environment: something that, given a name, can give you a value or a "I don't know an object with that name" error, and that you can give a (name,value) pair (a binding) to create (languages vary a bit in the way they handle the case where the name already is known)

In many languages, environments are nested. For example, in the example:

  var a = function() {
    var y = "bar";
    var z = "foo";
    window.getz = function() { return z; };
    
    var b = function() {
      window.bb = function() { z = y; };
    };
    
    var c = function() {
      window.cc = function() { z = y; };
    };

    var d = function() {
      var q = 42;
      window.dd = function() { z = q; };
    };

    b();
    c();
    d();
  };
  a()
Calling b, c, and d creates three environments. The environment created by calling d adds a binding of q to 42 to its environment; neither the one created by calling b nor the one created by calling c add bindings of its own, but conceptually, these two have their own environment. All three build on the environment of function a; that environment contains bindings for y and z

Normally, when leaving a block, the environment created when entering it can be discarded. Here, however, the environments still can be reached after execution of the block has ended; each of those environments becomes (part of) its own closure when the function returns. The closures created by calling c and by calling d are functionally identical because they both build on the same 'parent' environment and have no bindings of their own, but conceptually, each has its own closure.

More, better info at http://c2.com/cgi/wiki?LexicalClosure and, of course, in SICP, section 3.2 "The Environment Model of Evaluation" (although I remember seeing clearer pictures for that that involve making closures. Maybe they are in the videos?)




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: