简体   繁体   中英

javascript anonymous function with access to variable in creator

I need to access the i variable from the loop, in the success function. How do I do that?, can I pass it in to the function?

function save(){
    var mods=model.things;
    for (i in mods) {
        var mod= mods[i];
        $.ajax({
            url: "duck"
            type: "put",
            data: JSON.stringify(mod),
            success: function(responce_json) {
                var j=i;   
            }
        });
    }
}

One way:

        success: (function(i) { return function(responce_json) {
            var j=i;   
        }})(i)

This uses an Immediately Invoked Function Expression (IIFE) to create a closure that will capture the current value of i .

Incidently, for...in is considered bad practice by a lot of JavaScript programmers , but if you need to use it, you should probably at least include a check for hasOwnProperty

Create another function that takes i as a parameter thus creating a local copy for each iteration

var f = function(i) { 
    var mod= mods[i];
    $.ajax({
        url: "duck"
        type: "put",
        data: JSON.stringify(mod),
        success: function(responce_json) {
            var j=i;   
        }
    });
}
for (iter in mods) {
    f(iter);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM