错误示例:
const myService = {
func1: () => {},
func2: () => { func1()},
} // 报错 func1 is not defined no-undef
-
这个错误
func1 is not defined (no-undef)是因为在func2中调用func1时,JavaScript 找不到func1的定义。 -
代码中,
func1是myService对象的属性,而不是当前作用域内的变量。 -
箭头函数不会创建自己的
this,而是从父作用域继承this。 -
JavaScript 的箭头函数天然继承外部作用域的
this,类似于 C++ Lambda 中通过捕获列表([])传递外部变量。-
JavaScript 示例:
class MyClass { constructor() { this.value = 6; } method() { setTimeout(() => { console.log(this.value); // 自动绑定 this }, 1000); } } const obj = new MyClass(); obj.method(); // 输出 6 -
C++ 示例:
#include <iostream> #include <thread> using namespace std; class MyClass { public: int value = 6; void method() { thread([this]() { cout << this->value << endl; // 显式捕获 this }).join(); } }; int main() { MyClass obj; obj.method(); // 输出 6 return 0; }
-
正确的代码
方式一:
const myService = {
func1: () => {
console.log("Executing func1");
},
func2: function() {
this.func1(); // 使用 `this` 调用同一对象的方法
}
};
// 调用示例
myService.func2(); // 输出: Executing func1
方式二:使用 myService.func1() 的方式来显式调用对象的方法
const myService = {
func1: () => {
console.log("Executing func1");
},
func2: () => {
myService.func1(); // 显式引用对象本身
}
};
// 调用示例
myService.func2(); // 输出: Executing func1
577

被折叠的 条评论
为什么被折叠?



