# JavaScript closure的一个问题

stackoverflow的两个答案，合起来能很好的理解这个问题。

#### 1.进一步明白细节的回答

It has to do with when nAdd is assigned the function. Note that when you create a closure, a new “copy” (for lack of a better word) of the local variables are created. Thus, result1’s n is different from result2s n which is different from result3’s n. They are seperate, and each closure cannot access another closure’s n.

Look at this line:

This assigns nAdd a new closure each time. Each time, this closure will only affect the most recent “copy” of n.

So when you are doing.

nAdd got assigned a new closure each time. The last time, nAdd got assigned a closure with result3’s copy of n.

Thus, when you do nAdd(), you only increment result3’s n.

Here’s an example that might clear things up.

To further elaborate, consider what would happen if you did this instead:

Or this:

It becomes obvious that nAdd updates only the most recent invocation’s n.!

#### 2.调用本质的回答

First, you need to be clear about the following thing:

nAdd is a global scoped function. But it is using a local scoped variable n.

Every time you re-create f1(), the pointer of nAdd function will change.

Finally it will changed to the closest f1() closure and the n variable inside nAdd function will also point to the closest f1() closure. So it can only change the value of the closest one.

# JavaScript中this关键字

#### 译文

this 关键词是 JavaScript 一个常用的特性，但是它同时也是这门语言中最容易让人困惑或者误解的一个点。this 实际上是什么意思？如何去确定呢？

‘this’ 关键字对于其它程序化编程语言并不新奇，它经常指向一个类的构造函创建的新对象。举个例子：如果我有一个 Boat() 类，它含有一个 moveBoat() 方法，当在 moveBoat() 方法内部引用 this 的时候，我们实际上访问的是新创建的对象 Boat().

# 标签解析和JavaScript的闭包(Identifier Resolution and Closures in the JavaScript Scope Chain)

### 原文地址：http://davidshariff.com/blog/javascript-scope-chain-and-closures/#more-271

Scope = VO + All Parent VOs
Eg: scopeChain = [[VO] + [VO1] + [VO2] + [VO n+1]];

#### [VO]s

three() Scope Chain = [[three() VO] + [two() VO] + [one() VO] + [Global VO]]

#### 词法作用域

JavaScript的一个重要特征就是解释器使用了词法作用域，而不是动态作用域。复杂点来说，就是所有内部函数都会根据代码位置，静态地绑定到父级context上。

# 深入探讨JavaScript的执行环境和栈（What is the Execution Context & Stack in JavaScript）

#### 什么是Executin Context(执行上下文)

• 全局 code（Global code）——代码第一次执行的默认环境
• 函数 code（Function code）——执行流进入函数体
• Eval code（Eval code）——代码在eval函数内部执行

# JS函数式编程

### 一、概念相关

1. “函数式编程”是这种编程典范，它将电脑运算视为函数的计算。和指令式编程相比，函数式编程强调函数的计算比指令的执行重要；和过程化编程相比，函数式编程里，函数的计算可随时调用。
2. 函数式编程的重点是函数的定义而不是状态机（state machine）的实现
3. 函数式概念的运用，例如：扩展数组排序、动态HTML生成的优美代码、系列函数的应用。

1. 扩展数组排序

2. 系列函数应用