为什么不能访问对象的属性后,内部函数被改变了?

时间:2011-07-30 10:47:51

标签: javascript undefined

slider  = options.images[n];
//slider is an object with: title, src etc. properties but without "width" and "height" properties.
// so that i want to change/add those two proerties in preload function
if( slider.width == undefined || slider.width == 0 ){
    console.log('init for'+n);
    tSlider.preload(slider.src, function(){
        //this.width and this.height are real values
        slider.width = this.width;
        slider.height=this.height;
    });

    //why can not read the width and height?
    slider.width == undefined;// true
}

2 个答案:

答案 0 :(得分:0)

我认为可能this.width;也未定义,因此当您将其指定为滑块宽度时,它仍未定义

    slider.width = this.width;
    //this.width is undefined and so slider.width is undefined too

答案 1 :(得分:0)

如果您的预加载功能是异步的,并且只有在加载图像后才执行该回调,那么外部函数中的slider.width调用将始终为undefined。您需要等待回调执行,然后才检查属性。

这就是javasript中异步执行的工作方式。但是你的属性检查是在同步部分 - 即它不是在等待图像加载,它只是立即检查。

刚刚回答了类似的问题并提供了一个示例:请参阅How to send a return form a callback function to the main function