gpt4 book ai didi

javascript箭头函数: can we capture values like in c++ lambdas?

转载 作者:行者123 更新时间:2023-12-03 07:12:21 26 4
gpt4 key购买 nike

当定义一个 c++ lambda https://en.cppreference.com/w/cpp/language/lambda有一个捕获 block 捕获封闭范围内的变量值(至少如果变量是通过复制而不是通过引用捕获的)。因此,如果 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++) {
// The variable i is captured by copy:
byCopyCaptures[i] = [i](int j) {std::cout << "capture by copy: i is " << i << " and j is "<< j <<"\n";};
// The variable i is captured by reference:
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 等价物是什么?

最佳答案

我想说最接近的等价物是使用 immediately invoked function expression , 并传入要锁定的值。由于代码现在访问的是函数参数而不是原始变量,因此对原始变量的赋值无关紧要。例如:

let a = 'a';
let b = 'b';

((a, b) => {
setTimeout(() => {
console.log(a);
console.log(b);
}, 1000);
})(a, b);

a = 'new a';
b = 'new b';

由于我对所有内容都使用了相同的名称,因此可能会有点混淆什么是指什么,所以这里是具有唯一变量名称的相同内容:
let a = 'a';
let b = 'b';

((innerA, innerB) => {
setTimeout(() => {
console.log(innerA);
console.log(innerB);
}, 1000);
})(a, b);

a = 'new a';
b = 'new b';

关于javascript箭头函数: can we capture values like in c++ lambdas?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61762303/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com