无法访问外部函数中的变量

时间:2017-07-30 05:42:27

标签: javascript variables

var _URL = window.URL || window.webkitURL;

var $file = FS.gID('failImage');

var imgSize = FS.gID('failImage');

var file, img, imgWidth, imgHeight;


if(file = imgSize.files[0]) {

 img = new Image();

    img.onload = function() {

        imgWidth = this.width;
        imgHeight = this.height;


    }

    img.src = _URL.createObjectURL(file);

}

 alert(imgWidth); //Comes out undefined.

为什么我无法通过此变量来提醒imgWidth?请注意,我没有在子函数中设置var,但是当我去警告imgWidth时它在父函数中是不确定的?

1 个答案:

答案 0 :(得分:1)

因为img在此行执行后加载alert(imgWidth);

解决方案是在alert(imgWidth);函数中移动onload

if (file = imgSize.files[0]) {

    img = new Image();

    img.onload = function () {

        imgWidth = this.width;
        imgHeight = this.height;

        alert(imgWidth); // This should work

    }

    img.src = _URL.createObjectURL(file);

}

或使用回调函数

function afterLoad(width, height) {
    alert(width);
    alert(height);
}

if (file = imgSize.files[0]) {

    img = new Image();

    img.onload = function () {

        imgWidth = this.width;
        imgHeight = this.height;

        afterLoad(imgWidth, imgHeight);

    }

    img.src = _URL.createObjectURL(file);

}
相关问题