gpt4 book ai didi

javascript - 函数中的局部变量覆盖在循环中多次运行

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:48:31 25 4
gpt4 key购买 nike

嘿,我这里有一个小问题。

问题:我如何为一个函数创建唯一的变量,以便在多次调用时,变量将保留它们应该保留的内容(而不是交换)

请记住,我必须保持异步,因为循环会很大,不异步运行会严重影响性能

我有一个在 Canvas 上绘制项目的功能。然后我在 for 循环中运行这个函数,根据数组中的一些数据绘制一些 Canvas 。

简化版:

function renderCanvas(canvas, dID) {
var mName, bName, sName, tName;
this.layerCounter = mainData[dID]['layerCount'];
console.debug(designID + " has " + layerCounter + " layers");
/* that gives 2 layers for first item and 3 for second)*/

tctx2.clearRect(0, 0, tc2.width, tc2.height);
var imgPath = sName;
imgObj = new Image();
imgObj.src = "img/" + imgPath;
imgObj.onload = function () {

tctx2.drawImage(imgObj, 0, 0, w, h, 0, 0, dw, dh);
layerCounter--;
console.debug(designID + " has " + layerCounter + " layers");

tctx3.clearRect(0, 0, tc2.width, tc2.height);
var imgPath = tName;
imgObj = new Image();
imgObj.src = "img/" + imgPath;
imgObj.onload = function () {

tctx3.drawImage(talphaObj, 0, 0, w, h, 0, 0, dw, dh);
layerCounter--;
console.debug(designID + " has " + layerCounter + " layers");
};
}
}
for (var i = 0; i < xArr.length; i++) {
var cDID = xArr[i];
renderCanvas(contexts[i], cDID);
}

有什么建议吗?我对编程还很陌生,所以我可能遗漏了一些非常简单的东西。

最佳答案

像这样点击一个 javascript 函数(具有异步行为)你想使用闭包:

//im assuming contexts array is defined some where up here??

for (var i = 0; i < xArr.length; i++) {
var cDID = xArr[i];

//the following function will self execute on each loop
(function (c, d) {
//Insert your renderCanvas function body here
//but use variable c and d in this closure.
//The values you have passed into this closure
//are now 'fixed' in this scope and cannot
//be interfered with by subsequent iterations
})(contexts[i], cDID);
}});

基本上,您将函数包装在另一个范围内,以便在现在的异步循环的下一次迭代中,您无法覆盖局部变量(我认为这是您所指的变量被“交换”的行为)

这很好地解释了 javascript 闭包,它可能是一个令人困惑的主题! - How do JavaScript closures work?

关于javascript - 函数中的局部变量覆盖在循环中多次运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20975651/

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