Javascript onload事件未在对象内部激发

Javascript onload event not firing inside object

本文关键字:内部 对象 onload 事件 Javascript      更新时间:2023-09-26

我正试图弄清楚为什么这不起作用,并想知道是否有人能帮我。基本上,我需要具有不同图像的该对象的多个实例,并且我需要每个对象存储其关联图像的图像高度/宽度以供进一步操作,但是onload事件从未触发?

很抱歉,伙计们要清楚完整的代码,如果你看到TestTheVar函数imgW从未被设置为任何东西。

<script type="text/javascript">
  (function() {
  var myTest = new TestObj();
  mytest.TestTheVar();
  })();
function TestObj() {
  this.img = new Image();
  this.img.onload = function(){
    this.imgW = this.img.width;
    this.imgH = this.img.height;
  };
  this.img.src = "reel_normal.PNG";
  this.TestTheVar = function() {
    alert(this.imgW);
  }
}
</script>

这里有两个问题

1) 范围

2) 定时

其他答案中提到的范围是指onload函数中的thisImage对象,而不是您的TestObj,因此您需要执行以下操作:

<script type="text/javascript">
(function() {
    var myTest = new TestObj();
    mytest.TestTheVar();
})();
function TestObj() {
  var self = this;
  this.img = new Image();
  this.img.onload = function(){
    self.imgW = this.width;
    self.imgH = this.height;
  };
  this.img.src = "reel_normal.PNG";
  this.TestTheVar = function() {
    alert(this.imgW);
  }
}
</script>

时间是指当您试图访问高度和宽度时,您不能假设图像已经完成加载。这就是回调的好处:

<script type="text/javascript">
  (function() {
      var myTest = new TestObj(function() {
          myTest.TestTheVar();
      });
  })();
function TestObj(cb) {
  cb = cb || function() {};
  var self = this;
  this.img = new Image();
  this.img.onload = function(){
    self.imgW = this.width;
    self.imgH = this.height;
    cb();
  };
  this.img.src = "reel_normal.PNG";
  this.TestTheVar = function() {
    alert(this.imgW);
  }
}
</script>

this是属于每个函数的关键字。

load事件侦听器中,它将是映像,而不是您的TestObj实例。

因此,您可以

  • 使用this.img.imgW获取:

    function TestObj() {
      var that = this;
      this.img = new Image();
      this.img.onload = function(){
        this.imgW = this.width;
        this.imgH = this.height;
        that.testTheVar();
      };
      this.img.src = "reel_normal.PNG";
      this.testTheVar = function() {
        alert(this.img.imgW);
      };
    }
    
  • 将其存储在您的TestObj实例中:

    function TestObj() {
      var that = this;
      this.img = new Image();
      this.img.onload = function(){
        that.imgW = this.width;
        that.imgH = this.height;
        that.testTheVar();
      };
      this.img.src = "reel_normal.PNG";
      this.testTheVar = function() {
        alert(this.imgW);
      };
    }
    
  • 将事件处理程序中的this自定义为TestObj实例:

    function TestObj() {
      this.img = new Image();
      this.img.onload = (function(){
        this.imgW = this.img.width;
        this.imgH = this.img.height;
        this.testTheVar();
      }).bind(this);
      this.img.src = "reel_normal.PNG";
      this.testTheVar = function() {
        alert(this.imgW);
      };
    }