ily*_*lyo 4 javascript closures
在这种情况下,JavaScript闭包是如何工作的,更具体一点:(i)最终的作用是什么?
for(var i = 0; i < 10; i++) {
(function(e) {
setTimeout(function() {
console.log(e);
}, 1000);
})(i);
}
Run Code Online (Sandbox Code Playgroud)
此外,我正在尝试在我的代码中实现它,似乎我没有做对
for (var i=0; i < len; i++) {
var formID = document.forms["form-" + i];
$(formID).bind("submit", validate);
$(formID).bind("change", function(i){
var divI = '#ind-' + i;
$(divI).css("background-color","green");
})(i);
}
Run Code Online (Sandbox Code Playgroud)
Ray*_*nos 12
这是用于围绕变量创建局部范围的模式.如果没有使用,那么每次调用console.log(i)都会i在for循环结束后记录(10)的值.
for(var i = 0; i < 10; i++) {
// create new function
(function(e) {
// log each counter after 1 second.
setTimeout(function() {
console.log(e);
}, 1000);
// execute it with the counter
})(i);
}
Run Code Online (Sandbox Code Playgroud)
以上与此相同.
function foobar(e) {
setTimeout(function() {
console.log(e);
}, 1000);
}
for (var i = 0; i < 10; i++) {
(
foobar
)(i);
}
Run Code Online (Sandbox Code Playgroud)
这里真正的问题是在循环中创建函数.不要这样做:)
你的代码
for (var i=0; i < len; i++) {
var formID = document.forms["form-" + i];
$(formID).bind("submit", validate);
// create a full closure around the block of code
(function() {
$(formID).bind("change", function(i){
var divI = '#ind-' + i;
$(divI).css("background-color","green");
})//(i); Don't call (i) here because your just trying to execute the
// jQuery element as a function. You can't do this, you need to wrap
// an entire function around it.
})(i);
}
Run Code Online (Sandbox Code Playgroud)
但这是错误的,你想把这份工作委托给其他人.
function makeGreen(form, i) {
$(form).change(function() {
$("#ind-"+i).css("background-color", "green");
});
}
for (var i=0; i < len; i++) {
var formID = document.forms["form-" + i];
$(formID).bind("submit", validate);
// call a helper function which binds the change handler to the correct i
makeGreen(formID, i);
}
Run Code Online (Sandbox Code Playgroud)
如果你想变得有点聪明,你可以摆脱这些匿名功能
function makeGreen() {
var divId = $(this).data("div-id");
$(divId).css("background-color", "green");
}
for (var i=0; i < len; i++) {
$(document.forms["form-" + i])
.bind("submit", validate)
// store i on the form element
.data("div-id", "#ind-" + i)
// use a single event handler that gets the divId out of the form.
.change(makeGreen);
}
Run Code Online (Sandbox Code Playgroud)
编辑
( // contain the function we create.
function(parameterA) {
window.alert(parameterA);
}
) // this now points to a function
("alertMessage"); // call it as a function.
Run Code Online (Sandbox Code Playgroud)
是相同的
( // contain the window.alert function
window.alert
) // it now points to a function
("alertMessage"); // call it as a function
Run Code Online (Sandbox Code Playgroud)