Files
knowledge-kit/Chapter2 - Web FrontEnd/2.33.md
2020-02-25 17:46:51 +08:00

59 lines
1.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# ES6学习总结
## 闭包
匿名函数保存的是引用。看看下面代码例子
```javascript
var array = new Array();
// 实验1:
for (var index = 0;index < 3; index++) {
array.push(function(){
console.log(index)
})
}
array[1]() // 输出2
// 实验2
for (var index = 0; index < 3; index++) {
(function (n) {
array.push(function(){
console.log(n);
})
})(index)
}
array[1]() // 输出1
```
### 闭包与内存泄漏
js 内存控制主要是通过计数器。当某个对象 A 引用对象 B那么 B 的计数器加1若 A 释放掉了,那么 A 引用对于 B 的计数器将变为 0。若 B 的所有计数器变为0的时候那么 B 将会被释放。引用循环将会造成内存泄漏什么是引用循环A 引用 BB 引用 A会造成引用循环内存泄漏
正是因为闭包的这个特点,我们可以将闭包应用在某些场合。
### 闭包应用场合
- 封装
```javascript
var Person = function () {
var name = "LBP";
return {
getName () {
return 'I am ' + name;
},
setName (newName) {
name = newName;
}
}
}();
console.log(Person.name);
console.log(Person.getName());
Person.name = "杭城小刘";
Person.setName('杭城小刘');
console.log(Person.getName());
```
-