示例工程 04-functions-this

04-functions-this/03-arrow-this/README.md

markdown · 0.9 KB

运行:04 · 箭头函数与词法 this

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

# 03 · 箭头函数与词法 this
 
**演示**:箭头函数没有自己的 `this`,在定义时捕获外层 `this`;它适合做回调,不适合做对象方法。
**怎么看**:`node scripts/serve.mjs` 后打开 <http://localhost:8080/examples/04-functions-this/03-arrow-this/>,开 Console。
**预期输出**:
 
```text
场景 => 结果
map 里的箭头函数 => 42,42
map 里的普通函数(丢 this) => TypeError
箭头函数当对象方法 => TypeError
箭头函数在定义时捕获 this => true / ctx
--------------------------------------------------
要点:箭头函数没有自己的 this,取定义位置外层的 this;所以它不能当方法,也不能被 call/apply/bind 改变。
```
 
**注意**:箭头函数同时没有自己的 `arguments`、`super`、`new.target`,也不能用 `new` 调用。如果需要一个可被 `bind` 改 `this` 的回调,就不要用箭头函数。需 `http://` 协议。