Skip to content

Commit a67b578

Browse files
committed
docs(function): edit arrow function
1 parent 99dd289 commit a67b578

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

docs/function.md

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -660,7 +660,7 @@ function full(person) {
660660
箭头函数使得表达更加简洁。
661661

662662
```javascript
663-
const isEven = n => n % 2 == 0;
663+
const isEven = n => n % 2 === 0;
664664
const square = n => n * n;
665665
```
666666

@@ -852,6 +852,36 @@ foo(2, 4, 6, 8)
852852

853853
长期以来,JavaScript 语言的`this`对象一直是一个令人头痛的问题,在对象方法中使用`this`,必须非常小心。箭头函数”绑定”`this`,很大程度上解决了这个困扰。
854854

855+
### 不适用场合
856+
857+
由于箭头函数使得`this`从“动态”变成“静态”,下面两个场合不应该使用箭头函数。
858+
859+
第一个场合是定义函数的方法,且该方法内部包括`this`
860+
861+
```javascript
862+
const cat = {
863+
lives: 9,
864+
jumps: () => {
865+
this.lives--;
866+
}
867+
}
868+
```
869+
870+
上面代码中,`cat.jumps()`方法是一个箭头函数,这是错误的。调用`cat.jumps()`时,如果是普通函数,该方法内部的`this`指向`cat`;如果写成上面那样的箭头函数,使得`this`指向全局对象,因此不会得到预期结果。
871+
872+
第二个场合是需要动态`this`的时候,也不应使用箭头函数。
873+
874+
```javascript
875+
var button = document.getElementById('press');
876+
button.addEventListener('click', () => {
877+
this.classList.toggle('on');
878+
});
879+
```
880+
881+
上面代码运行时,点击按钮会报错,因为`button`的监听函数是一个箭头函数,导致里面的`this`就是全局对象。如果改成普通函数,`this`就会动态指向被点击的按钮对象。
882+
883+
另外,如果函数体很复杂,有许多行,或者函数内部有大量的读写操作,不单纯是为了计算值,这时也不应该使用箭头函数,而是要使用普通函数,这样可以提高代码可读性。
884+
855885
### 嵌套的箭头函数
856886

857887
箭头函数内部,还可以再使用箭头函数。下面是一个 ES5 语法的多重嵌套函数。

docs/reference.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@
9393
- Mark McDonnell, [Understanding recursion in functional JavaScript programming](http://www.integralist.co.uk/posts/js-recursion.html): 如何自己实现尾递归优化
9494
- Nicholas C. Zakas, [The ECMAScript 2016 change you probably don't know](https://www.nczonline.net/blog/2016/10/the-ecmascript-2016-change-you-probably-dont-know/): 使用参数默认值时,不能在函数内部显式开启严格模式
9595
- Axel Rauschmayer, [ES proposal: optional catch binding](http://2ality.com/2017/08/optional-catch-binding.html)
96+
- Cynthia Lee, [When you should use ES6 arrow functions — and when you shouldn’t](https://medium.freecodecamp.org/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26): 讨论箭头函数的适用场合
9697

9798
## 对象
9899

0 commit comments

Comments
 (0)