var circle={
"PI": 3.14159,
"Area": function (r) {
return this. PI * R * r;
}
};
Alert (Circle.area (1.0));
Anonymous self-executing functions
var data= {
Table: [],
Tree: {}
};
(function (DM) {
for (var i = 0; i < dm.table.rows; i++) {
var row = Dm.table.rows[i];
for (var j = 0; j < Row.cells; i++) {
Drawcell (i, j);
}
}
}) (data);
The result cache [Closure is exactly what you can do because it does not release external references, so the values inside the function can be preserved. ]
var Cachedsearchbox = (function () {
var cache = {},
Count = [];
return {
Attachsearchbox:function (DSID) {
if (Dsid in cache) {//If the result is in the cache
Return cache[dsid];//directly to the object in the cache
}
var FSB = new Uikit.webctrl.SearchBox (DSID);//New
CACHE[DSID] = fsb;//Update cache
if (Count.length > 100) {//Yasumasa cache size <=100
Delete Cache[count.shift ()];
}
return FSB;
},
Clearsearchbox:function (DSID) {
if (Dsid in cache) {
Cache[dsid].clearselection ();
}
}
};
})();
Cachedsearchbox.attachsearchbox ("input");
3. Encapsulation
var person = function () {
Variable scope is inside function, external unreachable
var name = "Default";
return {
Getname:function () {
return name;
},
Setname:function (newName) {
name = NewName;
}
}
}();
Print (person.name);//direct access with result of undefined
Print (Person.getname ());
Person.setname ("Abruzzi");
Print (Person.getname ());
4. Implementing Classes and Inheritance
function person () {
var name = "Default";
return {
Getname:function () {
return name;
},
Setname:function (newName) {
name = NewName;
}
}
};
var p = new person ();
P.setname ("Tom");
Alert (P.getname ());
var Jack = function () {};
Inherit from person
Jack.prototype = new Person ();
Adding Private methods
Jack.prototype.Say = function () {
Alert ("Hello,my name is Jack");
};
var j = new Jack ();
J.setname ("Jack");
J.say ();
Alert (J.getname ());
Source: http://www.cnblogs.com/yunfeifei/p/4019504.html
A comprehensive understanding of how JavaScript closures and closures are written and used