# MDN-闭包

### 我自己不太确定的地方和重要关键字就顺带挂上英文了. 顺带也可以学习下表达方式. 欢迎指正.

JS闭包到底是什么?

Closures are functions that refer to independent (free) variables (variables that are used locally, but defined in an enclosing scope). In other words, these functions 'remember' the environment in which they were created.

function init() {
var name = "Mozilla"; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert(name); // use variable declared in the parent function
}
displayName();
}
init();
init( ) 创建了一个局部变量name和内置的函数displayName( ),  这个内置函数就是闭包.它有以下特点:

1. 是 init( ) 中的一个内置函数(inner function), 并且只有在int( )内部可得(available).

2.在该例中没有自己的局部变量, 但可以使用外层函数(outer functions)的变量, 自然也包括了父级外层函数(parent function).

the code and see that this works. This is an example of lexical scoping: in JavaScript, the scope of a variable is defined by its location. within the source code (it is apparent lexically) and nested functions have access to variables declared in their outer scope.

1.JS中,变量的作用域范围取决于变量在源码中所处位置.(因此说作用域是lexical).

2.内置的函数可以获取外层函数的定义的变量

function makeFunc() {
var name = "Mozilla";    // name 是 local
function displayName() {
}
return displayName;
}

var myFunc = makeFunc();
myFunc();

A closure is the combination of a function and the lexical environment (or simply "environment") within which that function wasdeclared. The environment consists of any local variables that were in-scope at the time that the closure was created.

function makeAdder(x) {
return function(y) {
return x + y;
};
}
//创建两个函数并传入不同的参数

console.log(add10(2)); // 12

1.先给body中统一设置font-size,以px为单位;

2. 给所需元素设置font-size,用相对单位em

Java本身支持声明将方法声明为私有(declare methods private）,这样就可以保证方法只能被同一类下的其他方法调用.(can only be called by other methods in the same class)

JS可以通过闭包来模拟该方法.

2.可方便管理全局命名空间(global namespace), 维护页面整洁(keeping non-essential methods from cluttering up the public interface)

http://codepen.io/anon/pen/GrNabO?editors=1010

# What is lexical scope?http://stackoverflow.com/questions/1047454/what-is-lexical-scope

-anonymous-function-wrapper? http://stackoverflow.com/questions/4598479/what-is-the-purpose-of-the-anonymous-function-wrapper-in-jquery

03-06 1616

08-07 24
02-03 165
10-16 58
03-05
02-19 72万+
09-04
09-28
05-23