JavaScript 71 – progetto di un linguaggio di programmazione – 6

Continuo da qui, copio qui.
Continuo con gli esercizi.

Closure
The way we have defined fun allows functions in Egg to “close over” the surrounding environment, allowing the function’s body to use local values that were visible at the time the function was defined, just like JavaScript functions do.

The following program illustrates this: function f returns a function that adds its argument to f‘s argument, meaning that it needs access to the local scope inside f to be able to use variable a.

run("do(define(f, fun(a, fun(b, +(a, b)))),",
    "   print(f(4)(5)))");

Go back to the definition of the fun form and explain which mechanism causes this to work.

Uh! kwasy-panico 😯. Intanto creo il file clo.js inserendo nello script l’istruzione require, come già nell’esercizio del post precedente ed eseguo:

require("./load.js") ("/p-egg.js");

run("do(define(f, fun(a, fun(b, +(a, b)))),",
    "   print(f(4)(5)))");

OK, funziona 😎 La spiegazione del perché? cedo la parola a Marijn:

Again, we are riding along on a JavaScript mechanism to get the equivalent feature in Egg. Special forms are passed the local environment in which they are evaluated so that they can evaluate their subforms in that environment. The function returned by fun closes over the env argument given to its enclosing function and uses that to create the function’s local environment when it is called.

This means that the prototype of the local environment will be the environment in which the function was created, which makes it possible to access variables in that environment from the function. This is all there is to implementing closure (though to compile it in a way that is actually efficient, you’d need to do some more work).

:mrgreen:

Annunci
Post a comment or leave a trackback: Trackback URL.

Trackbacks

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...

%d blogger hanno fatto clic su Mi Piace per questo: