nodejs26: 箭头函数(=>)域继承问题

错误示例:

const myService = {
 func1: () => {},
 func2: () => { func1()},
} // 报错 func1 is not defined  no-undef
  • 这个错误 func1 is not defined (no-undef) 是因为在 func2 中调用 func1 时,JavaScript 找不到 func1 的定义。

  • 代码中,func1myService 对象的属性,而不是当前作用域内的变量。

  • 箭头函数不会创建自己的 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值