问题:如何为函数创建唯一变量,因此当多次调用时,变量将保留它们应该存在的内容(不交换)
请记住,我必须让它保持异步,因为循环会很大并且没有运行它async会很难达到性能
我有一个在画布上绘制项目的功能。然后我在for循环中运行这个函数,根据数组中的一些数据绘制一些画布。
如此简化的版本:
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);
}
有什么建议吗?我对编程很新,所以我可能很容易错过一些东西。
答案 0 :(得分:6)
点击一个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);
}});
基本上你将函数包装在另一个作用域中,这样在现在的async循环的下一次迭代中你就不能覆盖你的局部变量(我认为这是你所引用的'swapped'变量的行为)
这给出了javascript闭包的一个很好的解释,它可能是一个令人困惑的主题! - How do JavaScript closures work?