Why is this not working?
var img = new Image();
this.dimensions = [ ];
var m = this;
img.onload = function(){
return function(){
m.dimensions = [ this.width, this.height ];
}
};
img.src = 'images/whatever.jpg';
console.log(this.dimensions);
[]
(inside of a JS object, hence the “this”)
EDIT: working code
var img = new Image();
this.dimensions = [ ];
var m = this;
img.onload = function(){
m.dimensions.push(this.width, this.height);
console.log(m.dimensions) // had to wait
};
img.src = 'whatever.jpg';
Are you sure console.log(this.dimensions) is being run AFTER the image has loaded? What you’ve added to img.onload is a callback function to run after the image has finished loading in DOM. Until that img has finished loading, m.dimensions will not be set yet. The image does not load immediately when you add the callback, but loads asynchronously and can finish whenever.
In other words, you are running console.log(this.dimensions) before the dimensions has been set yet (before the onload callback is run). I bet if you wrapped the console.log inside a setTimeout call with say 5 seconds, then it would log what you expected.