简体   繁体   English

javascript匿名函数,可访问创建者中的变量

[英]javascript anonymous function with access to variable in creator

I need to access the i variable from the loop, in the success function. 我需要在成功函数中从循环访问i变量。 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 . 这使用立即调用函数表达式(IIFE)创建一个闭包,该闭包将捕获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 顺便说一下, for...in ,许多JavaScript程序员都认为这是不好的作法,但如果您需要使用它,则可能至少应包括对hasOwnProperty的检查

Create another function that takes i as a parameter thus creating a local copy for each iteration 创建另一个将i作为参数的function ,从而为每次迭代创建一个本地副本

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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