0

Is there a way I can refer to the class object, in the image.onload? this refers to the image itself. How I can refer to the Texture object?

https://jsfiddle.net/yL648t40/

function Texture(url){
  this.image = new Image();
  this.image.src = url;
  this.image.onload = function(){
    this.width = this.image.width;
    this.height = this.image.height;
  }
}

text = new Texture("http://opengameart.org/sites/default/files/styles/watermarked/public/bone2-equus_hemionus.png");

document.body.innerHTML += text.image + "<br>";
document.body.innerHTML += text.image.src + "<br>";
document.body.innerHTML += text.image.width + "<br>";

I've tried using something like this inside the Texture class

self = this;
this.image.onload = function(self){
    self.width = self.image.width;
    self.height = self.image.height;
}

But obiviously it doesn't work

  • `self` works when you declare it properly as `var self = …` and remove it from the parameter list. – Bergi Sep 13 '16 at 19:18

2 Answers2

1

You have to remove the self argument from your handler:

self = this;
this.image.onload = function(){ 
  self.width = self.image.width;     
   self.height = self.image.height;
}

Another option would be to bind the function to this, but that's complicated using pure javascript.

Nicolai Ehemann
  • 574
  • 4
  • 10
0

You have sevaral options.

First: Use the self workaround as suggested by this answer.

Second: Use Function.bind like this.

function Texture(url){
  this.image = new Image();
  this.image.src = url;

  var loadHandler = function(){
    this.width = this.image.width;
    this.height = this.image.height;
  };

  this.image.onload = loadHandler.bind(this);
}

Third: Use ES6 arrow functions, which will preserve the this context in their bodies (if your environment can afford ES6). Here is a good article.

Community
  • 1
  • 1
Zoltán Tamási
  • 12,249
  • 8
  • 65
  • 93