Spot 这个 Binding Mistake
找错误 中等
题目
这个 code throws 错误 or gives 错误输出. 什么是 issue?
代码
const obj = {
name: "Ada",
greet() { return "Hello, " + this.name; }
};
const fn = obj.greet;
console.log(fn());
提示
这个 depends on 如何函数是 called, 不哪里它 是定义.
解释
When obj.greet is extracted into fn and called as fn(), this is undefined (in strict mode) or the global object — not obj. So this.name is undefined. The fix is to use .bind(obj): const fn = obj.greet.bind(obj);, or call it as obj.greet() directly, or use an arrow function that captures this lexically.
相关资源
相关课程
- JavaScript 对象
学习关于这个 binding.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。