javascript箭头功能:我们可以像在c ++ lambdas中那样捕获值吗?

问题描述 投票:0回答:1

定义c ++ lambda https://en.cppreference.com/w/cpp/language/lambda时,有一个捕获块可以捕获封闭范围内变量的values(至少在变量是通过复制而不是通过引用捕获的情况下)。因此,如果lambda使用已捕获的变量,并且稍后执行lambda,则lambda内部的各个变量将具有定义lambda时的值。]

使用javascript箭头功能,我可以从封闭范围引用变量。但是,当箭头函数被调用时,它将使用它现在具有的变量的值(而不是定义箭头函数时的值)。

是否有类似的变量捕获机制,可以将捕获的变量值与箭头函数对象一起存储?

这里是一个c ++示例:

// Example program
#include <iostream>
#include <string>
#include <functional>

int main()
{
  std::function<void(int)> byCopyCaptures[5];
  std::function<void(int)> byRefCaptures[5];
  for(int i=0; i<5; i++) {
      byCopyCaptures[i] = [i](int j) {std::cout << "capture by copy: i is " << i << " and j is "<< j <<"\n";};
      byRefCaptures[i] = [&i](int j) {std::cout << "capture by ref:  i is " << i << " and j is "<< j <<"\n";};
  }
  for(int k=0; k<5;  k++) {
      byCopyCaptures[k](k);
      byRefCaptures[k](k);
  }
}

输出:

capture by copy: i is 0 and j is 0
capture by ref:  i is 5 and j is 0
capture by copy: i is 1 and j is 1
capture by ref:  i is 5 and j is 1
capture by copy: i is 2 and j is 2
capture by ref:  i is 5 and j is 2
capture by copy: i is 3 and j is 3
capture by ref:  i is 5 and j is 3
capture by copy: i is 4 and j is 4
capture by ref:  i is 5 and j is 4

使用箭头功能的javascript相当于什么?

javascript c++ lambda arrow-functions
1个回答
1
投票

我想说的最接近的等效项是使用immediately invoked function expression,并传递您想要锁定的值。由于代码现在正在访问函数参数而不是原始变量,因此请更改为原始变量无关紧要。例如:

© www.soinside.com 2019 - 2024. All rights reserved.