1、执行嵌套函数(方法)
var x = "global";
function f() {
var x = "local";
function g() { alert(x); }
g();
}
f(); // Calling this function displays "local"
2、返回函数指针
// This function returns a function each time it is called
// The scope in which the function is defined differs for each call
function makefunc(x) {
return function() { return x; }
}
// Call makefunc() several times, and save the results in an array:
var a = [makefunc(0), makefunc(1), makefunc(2)];
// Now call these functions and display their values.
// Although the body of each function is the same, the scope is
// different, and each call returns a different value:
alert(a[0]()); // Displays 0
alert(a[1]()); // Displays 1
alert(a[2]()); // Displays 2
3、闭包(简单来讲,通过函数嵌套实现类的封装。即私有(private)属性需通过公用(public)方法赋值与取值。)
function makeProperty(o, name, predicate) {
var value; // This is the property value
// The setter method simply returns the value.
o["get" + name] = function() { return value; };
// The getter method stores the value or throws an exception if
// the predicate rejects the value.
o["set" + name] = function(v) {
if (predicate && !predicate(v))
throw "set" + name + ": invalid value " + v;
else
value = v;
};
}
// The following code demonstrates the makeProperty() method.
var o = {}; // Here is an empty object
// Add property accessor methods getName and setName()
// Ensure that only string values are allowed
makeProperty(o, "Name", function(x) { return typeof x == "string"; });