Part I. Language as a Computational Model7 min · en inglés

03

Functions as Data

Functions in JavaScript were values from day one: they were put into variables and object properties and called from there, the way the point constructor in the previous chapter did. Declaring a function inside another function, however, JavaScript 1.0 and 1.1 did not allow. All functions lived at the top level of a script and had nothing to remember except global variables. A language sold inside the company as Scheme for the browser went two years without the main thing Scheme has: closures.

The difference between a function and a closure seems like hair-splitting until you try to live without closures. A function that remembers nothing is little more than the address of a piece of code, like a function pointer in C. Everything it needs to work has to be passed in as arguments or put into global variables. A closure carries away the variables of the place where it was created and keeps seeing them even after the function it was born in has long finished. Scheme was built on closures as early as 1975. JavaScript got them in version 1.2, with Netscape 4 in 1997, and since then every function declared inside another is born anew on every call of the outer one, with its own set of variables.


Over time closures became JavaScript’s substitute for everything the language lacked: modules, namespaces, private fields. All the code on a page lived in one shared global object, and if two libraries each declared a function init, the second silently overwrote the first. People saved themselves like this: declare a function and call it immediately, hiding everything that mattered inside.

var Cart = (function () {
  var items = [];                     // invisible from outside
  function total() { /* ... */ }
  return {
    add: function (item) { items.push(item); },
    total: total
  };
})();

In 2007 Eric Miraglia described this technique on the Yahoo blog and named it the «module pattern», after which for about ten years nearly every library began with such a parenthesis. In 2009 Node built an entire module system on the same technique. Before executing a file, Node wraps it in a function and passes it exports, require and module:

Gratis, solo falta un paso

El resto del libro es gratis

Deja tu correo y te mando un enlace para confirmarlo. Después del clic, todos los capítulos se abren aquí, en este dispositivo, durante un año. Cuando salga un libro nuevo, escribiré a esa dirección; responde “basta” a cualquier correo y no vuelvo a escribir.

¿Tienes cuenta INITE? Entra y el libro se abre sin correo.

No se cobra nada por el libro. Si quieres apoyarlo, puedes donar desde cualquier capítulo.

Cómo se guarda la dirección