Javascript 为什么在内部函数&xFF1F;发生更改后无法访问对象的属性;

Javascript 为什么在内部函数&xFF1F;发生更改后无法访问对象的属性;,javascript,undefined,Javascript,Undefined,我认为很有可能this.width也是未定义的,因此当您将其分配到滑块宽度时,它仍然未定义 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(

我认为很有可能
this.width也是未定义的,因此当您将其分配到滑块宽度时,它仍然未定义

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
}

如果预加载函数是异步的,并且它只在加载图像后执行回调,那么外部函数中的
滑块.width
调用将始终是
未定义的
。您需要等待回调执行,然后才检查属性

这就是javasript中异步执行的工作方式。但是您的属性检查在同步部分,也就是说,它不是等待图像加载,而是直接检查


刚才回答了一个类似的问题并提供了一个示例:请参见

tSlider.preload做什么?它是否使用
this
值调用其第二个参数(函数),该值具有
width
height
属性?
    slider.width = this.width;
    //this.width is undefined and so slider.width is undefined too