开发者

Why can not acces the property of object after which had been changed inner function?

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
}


If your preload function is asynchronous, and it only executes that callback once it's loaded the image then your slider.width call in the outer function will always be undefined. You need to wait for the callback to execute, and only then check the property.

That's the way asynchronous execution works in javasript. But your property check is in the synchronous section - i.e. it's not waiting for the image to load, it's just checking straight away.

Just answered a similar question and provided an example: See How to send a return form a callback function to the main function


I think that problably this.width; is undefined too and so when you assing it to slider width it remains undefined

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜