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,227
  • 4
  • 18
  • 28

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
  • 155,085
  • 27
  • 166
  • 222
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,183
  • 3
  • 25
  • 67