0

I got this code:

_getWidthAndHeight = (ImageURL) => { 
    var img = new Image();
    img.onload = () => {
      alert(JSON.stringify(img));
      alert(this.height);
      alert(this.width);
    };
    img.src = ImageURL;
  }

It is supposed to load the image in google chrome, and get image height and width. Why the object returns empty?

Jacs
  • 1,437
  • 4
  • 21
  • 31

2 Answers2

1

this is not pointing at what you need in arrow functions

_getWidthAndHeight = (ImageURL) => { 
    var img = new Image();
    img.onload = function()  { // now "this" will be what you think it is
      console.log(this.height,this.width);
    };
    img.src = ImageURL;
  }
  
  _getWidthAndHeight("https://via.placeholder.com/500x400?text=500x400")

With arrow:

_getWidthAndHeight = (ImageURL) => { 
    var img = new Image();
    img.onload = (e) =>  { // now you can use e.target
      console.log(e.target.height,e.target.width);
    };
    img.src = ImageURL;
  }
  
  _getWidthAndHeight("https://via.placeholder.com/500x400?text=500x400")
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

The problem is that you're using this inside an ES6 arrow function. It has a different context from classic JS functions. You'll have to use this code for it to work:

_getWidthAndHeight = (ImageURL) => { 
    var img = new Image();
    img.onload = function () {
      alert(JSON.stringify(img));
      alert(this.height);
      alert(this.width);
    };
    img.src = ImageURL;
  }
Amar Syla
  • 3,523
  • 3
  • 29
  • 69