JavaScript: Closure, and Function with State

, , …,
Want to master JavaScript in a week? Buy Xah JavaScript Tutorial.

Function with State, Using Properties

JavaScript function is a object 〔➤ What's Object in JavaScript?〕, so it has properties, and we can use the properties to maintain state. Example:

// example of closure using properties, function with state

function f () {
    f.x += 1;
    return f.x;
}

f.x = 0;  // x is a property, used as state

console.log(f());               // 1
console.log(f());               // 2
console.log(f());               // 3

Closure Using Variable Scope

Here's a example of closure using JavaScript variable scope.

function closure_context() {
    var x = 0;
    function f() {
        x += 1;
        return x;
    }
    return f;
}

var closure = closure_context();

console.log(closure());         // 1
console.log(closure());         // 2
console.log(closure());         // 3

In this example, the closure_context() function returns the function f.

closure_context() sets up a variable x, and the inner function f uses it. When closure_context() is called, f is returned. The function f still has its scope context. (JavaScript function retains its original lexical scope chain.)

Remember, JavaScript scope is function based, and lexical scope. 〔➤ JavaScript Variable Scope: Function Level vs Block Level

Closure with Shared Variable Context

More than one function can share the same variable context.

function closure_context() {
    var x = 0;

    return {
        "f": function () { x += 1; return x; },
        "g": function () { x -= 1; return x; },
    };
}

var closure = closure_context();

console.log(closure.f());         // 1
console.log(closure.f());         // 2
console.log(closure.f());         // 3

console.log(closure.g());         // 2
console.log(closure.g());         // 1
console.log(closure.g());         // 0

Here, the function closure_context returns a object, and the object has 2 properties, each's value is a function.

blog comments powered by Disqus