Where ‘this’ executes? #3
dengshicheng1996
started this conversation in
Web
Replies: 1 comment
-
分析
解题第一次打印// 🟢 声明 test 变量,此时函数未发生调用。
const test = obj.test;
// 🟢 函数执行执行上下文为 window, 此时 this 指向 window,即 `this.name` 就是 `window.name`。
// 🟢 问题变为 window 下的 name 是什么?
// 🟢 let 声明的变量不会将 name 绑定到 window 下,所以不可能输出 `global`。
// 🟢 而 `window.name` 恰巧是 window 自有属性,默认值为空字符串。(这个是挖坑)
// 🟢 如果换成其他属性,如 `this.aaa` 之类的,则输出 `undefined`。
// ✅ 所以输出空字符串。
test(); 第二次打印// 🟢 对于 obj.test() 来说,我们只需要记住,谁调用了函数,谁就是 this。
// 🟢 所以在这个场景下 test 函数中的 this 就是 obj 对象。
// ✅ 所以输出 “obj”。
obj.test(); 参考资料 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
What will each output?
Beta Was this translation helpful? Give feedback.
All reactions