Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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?)



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

Search: