【问题标题】:Why can not acces the property of object after which had been changed inner function?为什么不能访问已更改内部函数的对象的属性?
【发布时间】:2011-07-30 22:27:58
【问题描述】:
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
}

【问题讨论】:

  • tSlider.preload 有什么作用?它是否使用具有widthheight 属性的this 值调用其第二个参数(函数)?

标签: javascript undefined


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-23
      • 1970-01-01
      • 1970-01-01
      • 2012-05-28
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多