示例工程 04-functions-this
04-functions-this/01-this-binding-forms/README.md
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
# 01 · this 的四种调用形式
**演示**:默认绑定、隐式绑定、显式绑定、`new` 绑定,以及 `new > bind > 隐式 > 默认` 的优先级;箭头函数的词法 `this`。
**怎么看**:`node scripts/serve.mjs` 后打开 <http://localhost:8080/examples/04-functions-this/01-this-binding-forms/>,开 Console。
**预期输出**:
```text
场景 => 结果
默认绑定:脱离对象调用 => undefined
隐式绑定:obj.getName() => obj
显式绑定:call / apply / bind => {"call":"explicit","apply":"explicit","bind":"explicit"}
new 绑定 => {"name":"Ada","isInstance":true}
优先级:new > bind => new-target
优先级:bind > 隐式 => bound
箭头函数忽略 .call 的 this => {"calledWithOther":true,"capturedIsUndefined":true}
箭头函数不能 new => TypeError
--------------------------------------------------
要点:this 由调用点决定(箭头函数除外)。优先级:new > 显式 bind > 隐式 obj.f() > 默认。
```
**注意**:示例运行在模块里,模块自动严格模式,所以「默认绑定」得到 `undefined`。如果把同样的代码放进非严格脚本,默认绑定会得到 `globalThis`——这是 `this` 行为在旧代码里看起来更混乱的主要原因。需 `http://` 协议。