【发布时间】:2014-04-11 10:16:37
【问题描述】:
以下示例在 for 循环中使用了闭包机制
我知道闭包的目的,但我不知道以下代码之间的最佳选择是什么,尤其是为什么一个会比另一个更好?
// First case: Closure wraps the ajax call
$('#container').on('click', 'a.log', function (e) {
_t = this;
for (var i = 0; i < 5; i++) {
(function (j) {
$.ajax({
url: "/logger",
context: _t
}).done(function () {
$(this).addClass("done" + j);
});
})(i);
};
});
// -------------------------------------------------------
// Second case :closure wraps the ajax callback function
$('#container').on('click', 'a.log', function (e) {
for (var i = 0; i < 5; i++) {
$.ajax({
url: "/logger",
context: this
}).done(
(function (j) {
return function () {
$(this).addClass("done" + j);
};
})(i)
);
};
});
我希望有人能准确地解释我。
感谢您的关注和花费的时间。
【问题讨论】:
-
没什么区别,但我个人会使用第一种情况,因为它更明显地表明我正在“锚定”循环值。
标签: javascript jquery closures