在侧面自调用函数中更新外部范围对象?

时间:2015-01-27 09:30:37

标签: javascript closures self-invoking-function

任何人都可以帮我理解我在做什么错吗? 或者帮我提供一个替代解决方案?

http://jsfiddle.net/mrrajesh1982/eynpu8rj/2/

  function isValidImageUrl(url, callback) {
    $('<img>', {
        src: url,
        load: function() {
            callback(true);
        },
        error: function() {
            callback(false);
        }
    });
}
var ndata = [{imgUrl: "https://library.barnard.edu/sites/default/files/paired_t_test_output_1_and_2.png"},{imgUrl: "url1"},{imgUrl: "http://statistics-help-for-students.com/How_do_I_report_paired_samples_T_test_data_in_APA_style_files/image002.jpg"}];


for (var i = 0; i < ndata.length; i++){
    var imageUrl = ndata[i].imgUrl;
    (function(pictureUrl){
        isValidImageUrl(pictureUrl, function(result) {
            if (!result) {
                ndata[i].imgUrl = "http://media.tcc.fl.edu/webcourses/ctll/Developing_Your_Teaching_Philosophy/examples.jpg";
                //I am getting error on this line as TypeError: ndata[i] is undefined

                //My question here is to how to update the ndata array obejct with valid image URL? 
            }
        });
    }(imageUrl));
}
console.log(JSON.stringify(ndata));// Expecting ndata[1].imgUrl should get updated inside self invoking function with valid image url

1 个答案:

答案 0 :(得分:0)

  function isValidImageUrl(url, callback) {
    $('<img>', {
        src: url,
        load: function() {
            callback(true);
        },
        error: function() {
            callback(false);
        }
    });
}
var ndata = [{imgUrl: "https://library.barnard.edu/sites/default/files/paired_t_test_output_1_and_2.png"},{imgUrl: "url1"},{imgUrl: "http://statistics-help-for-students.com/How_do_I_report_paired_samples_T_test_data_in_APA_style_files/image002.jpg"}];


for (var i = 0; i < ndata.length; i++){
    var imageUrl = ndata[i].imgUrl;
    (function(pictureUrl, i){
        isValidImageUrl(pictureUrl, function(result) {
            if (!result) {
                ndata[i].imgUrl = "http://media.tcc.fl.edu/webcourses/ctll/Developing_Your_Teaching_Philosophy/examples.jpg";
                //I am getting error on this line as TypeError: ndata[i] is undefined

                //My question here is to how to update the ndata array obejct with valid image URL? 

            console.log(ndata);
            }
        });
    }(imageUrl, i));
}

除了传递imageUrl之外,您还需要将i传递给您的匿名函数,否则它在回调运行时已经丢失了它的值。

另一件事是,在回调运行之前,您正在运行console.log()。您需要在回调中记录。另请注意,不保证它会按顺序返回。