In computer science, a closure is a function together with a referencing environment for the nonlocal names (free variables) of that function.
从技术上来讲,在JS中,每个function都是闭包,因为它总是能访问在它外部定义的数据。
Since scope-defining construction in Javascript is a function, not a code block like in many other languages, what we usually mean by closure in Javascript is a fuction working with nonlocal variables defined in already executed surrounding function.
闭包经常用于创建含有隐藏数据的函数(但并不总是这样)。
var db = (function() {
// 创建一个隐藏的object, 这个object持有一些数据
// 从外部是不能访问这个object的
var data = {};
// 创建一个函数, 这个函数提供一些访问data的数据的方法
return function(key, val) {
if (val === undefined) { return data[key] } // get