Skip to content

Commit

Permalink
void 0
Browse files Browse the repository at this point in the history
  • Loading branch information
alsotang committed Nov 12, 2014
1 parent 1915ee5 commit 7c27e39
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
26 changes: 26 additions & 0 deletions lesson11/README.md
Expand Up @@ -105,6 +105,32 @@ console.log(add20(5));

我暂时想不出什么实用的例子来,如果想深入理解这块,可以看看这篇 http://coolshell.cn/articles/6731.html

#### 闭包的一个坑

```js
for (var i = 0; i < 5; i++) {
setTimeout(function () {
console.log(i);
}, 5);
}
```

上面这个代码块会打印五个 `5` 出来,而我们预想的结果是打印 1 2 3 4 5。

之所以会这样,是因为 setTimeout 中的 i 是对外层 i 的引用。当 setTimeout 的代码被解释的时候,运行时只是记录了 i 的引用,而不是值。而当 setTimeout 被触发时,五个 setTimeout 中的 i 同时被取值,由于它们都指向了外层的同一个 i,而那个 i 的值在迭代完成时为 5,所以打印了五次 `5`

为了得到我们预想的结果,我们可以把 i 赋值成一个局部的变量,从而摆脱外层迭代的影响。

```js
for (var i = 0; i < 5; i++) {
(function (idx) {
setTimeout(function () {
console.log(idx);
}, 5);
})(i);
}
```

### this

在函数执行时,this 总是指向调用该函数的对象。要判断 this 的指向,其实就是判断 this 所在的函数属于谁。
Expand Down
2 changes: 1 addition & 1 deletion lesson14/README.md
Expand Up @@ -13,7 +13,7 @@ http://book.douban.com/subject/3590768/

js 这门语言,水很浅。没有太复杂的地方可以钻,但特么的坑又多。

上面的那本书是一定要看的。
上面的那本书是一定要看的。这本书专注在讲 js 语法,其他 js 的书都过多地涉及了浏览器知识。

### JavaScript 之美

Expand Down

0 comments on commit 7c27e39

Please sign in to comment.