Closures

Description

Closures are functions that have access to variables from another function's scope.

This is accomplished by creating a function inside a function:

Example


function createComparisonFunction(propertyName) {
//w w w .ja v  a2s  . c  o  m
    return function(object1, object2){
        var value1 = object1[propertyName];
        var value2 = object2[propertyName];

        if (value1 < value2){
            return -1;
        } else if (value1 > value2){
            return 1;
        } else {
            return 0;
        }
    };
}
var compare = createComparisonFunction("name");
var result = compare({ name: "XML" }, { name: "CSS" });

The inner function's scope chain includes the scope of createComparisonFunction().





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions