第 5 章 · 对象

方法调用与 this 绑定模拟器

同一个 describe() 函数被两个对象共享。切换调用表达式,观察函数运行时的 this 到底指向谁。

account.describe === guest.describe 结果为 true:函数相同,绑定不同
选择调用方式
当前函数使用严格模式
运行时指向
共享函数:describe
表达式 account.describe()
account
name"小明"
role"账户"
describe同一个函数
describe() 读取 this.name 和 this.role
guest
name"游客"
role"访客"
describe同一个函数
this → account
undefined

严格模式下,普通函数独立调用不会自动把 this 变成 window。

this 指向 account
返回值

"小明(账户)调用了共享的 describe()"

方法调用看点左边:account.describe() 中,点前面的 account 会成为 this