JavaScript

Closures

var x = "global";
function f() {
    var x = "local";
    function g() { //creates a closure
        alert(x);
    };
    return g();
}
x;

f();

var x = "global";
function f2() {
        var x = "local";
        function g() { //creates a closure
                alert(x);
        };
        return g;
}
var g = f2();
x;

g();

function makefunc(x) {
        return function() {
                return x;
        }
}

var a = [makefunc(0), makefunc(1), makefunc(2)];

a[0]();

a[1]();

a[2]();


José M. Vidal .

49 of 65