-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
91 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
# 箭头函数 | ||
|
||
### 写法灵活 | ||
``` | ||
const numbers = [2, 4, 7, 89, 234]; | ||
const double = numbers.map(function (number) { | ||
return number * 2; | ||
}); | ||
const double2 = numbers.map((number) => { | ||
return number * 2; | ||
}); | ||
console.log(double2); | ||
``` | ||
|
||
以上,两种语法, `double` 与 `double2` 结果一样。 | ||
|
||
简而言之: | ||
* 删掉 `function` 关键字 | ||
* 加上一个 `=>` 箭头 | ||
* 没有参数加 `()` | ||
* 一个参数可选择加 `()` | ||
* 多个参数 `,` 分隔 | ||
|
||
### 隐式返回 | ||
> 显示返回就是 `return` 关键字加上后面返回的内容 | ||
箭头函数中的隐士返回就是可以把 `renturn` 省略掉,去掉花括号 `{}`。 | ||
|
||
``` | ||
const double2 = numbers.map(number => number * 2); | ||
``` | ||
|
||
# this | ||
|
||
``` | ||
const Dp = { | ||
name: 'Dp', | ||
hobbies: ['Coding', 'Sleeping', 'Reading'], | ||
printHobbies: function () { | ||
this.hobbies.map(function (hobby) { | ||
console.log(`${this.name} loves ${hobby}`); | ||
}); | ||
} | ||
} | ||
Dp.printHobbies(); | ||
``` | ||
|
||
以上,结果是 | ||
``` | ||
undefined loves Coding | ||
undefined loves Sleeping | ||
undefined loves Reading | ||
``` | ||
|
||
原因 `this` 是在运行的时候绑定的,在以上 `map` 方法中的回调函数是一个独立的函数,当一个函数独立运行的时候,不是被作为对象的方法调用,也没有通过当没有 `apply` , `bind` , `call` 改变 `this` 值的话,这时候的 `this 指向 `window`。 | ||
|
||
所以我们可以改写 | ||
``` | ||
var self = this; | ||
this.hobbies.map(function (hobby) { | ||
console.log(`${self.name} loves ${hobby}`); | ||
}); | ||
``` | ||
达到想要的效果。 | ||
|
||
我们还可以利用箭头函数的便利 | ||
``` | ||
this.hobbies.map(hobby => console.log(`${this.name} loves ${hobby}`)); | ||
``` |