我在 jqgrid(一个 jquery 网格)中使用以下函数闭包来保留在名为“retainedChanges”的变量中进行分页时编辑的更改 - 这看起来不错吗?我打破了 javascript 中的任何良好做法; 代码工作正常只是想确保我不会引入将来可能会破坏的功能
(function($){
var retainedChanges;
retainedChanges = new Array();
$.retainChangesOnPaging = function(){
var changedCells = $('#grid').jqGrid('getChangedCells');
// loop over changedCells array, removing duplicates if you want to...
return retainedChanges.push(/* this is inside the loop; push current value to array*/);
....
}
$.getRetainedChanges = function(){
return retainedChanges;
}
})(jQuery);
最佳答案
虽然您应该接受 jQuery 作为参数,但它工作正常:
(function($){
这样,即使 $
符号被用于闭包之外的其他东西,它也不会影响闭包内的代码。
还有2件事:
1) 您应该一起声明和分配您的变量,并使用 []
而不是 new Array()
。
2) 你在这里缺少一个 $
符号:('#grid')
。
要了解完整的概要,请看这个:
(function($){
var retainedChanges = [];
$.retainChangesOnPaging = function(){
var changedCells = $('#grid').jqGrid('getChangedCells');
// loop over changedCells array, removing duplicates if you want to...
return retainedChanges.push(/* this is inside the loop; push current value to array*/);
....
}
$.getRetainedChanges = function(){
return retainedChanges;
}
})(jQuery);
关于javascript - 我的 javascript 闭包写得正确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8736430/