Entitize
Entitize

Reputation: 4969

Javascript Classes Property not being read


The properties x,y,width,height are not being read! When I do .drawImage(), this.x, this.y, this.width, this.height are not being used!

Say I changed the x the image won't change its position. However, if I alert(this.x) or any variable, then it will print out the correct value.

Thanks for the community help!

var Enemy = function(word, x, y, width, height) {

  this.word = word;

  //Position of the Enemy Spawn
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
}
Enemy.prototype.draw = function() {
  var image = new Image();
  image.onload = function() {
    Context.context.drawImage(image, this.x, this.y, this.width, this.height)
  };
  image.src = "enemy.png"
  // If I do alert(this.x), it returns the correct value!!!
}

This is the initialization:

var myEnemy = new Enemy("TestEnemy", 100, 100, 100, 100);
myEnemy.draw();

Upvotes: 1

Views: 39

Answers (2)

Steven Anderson
Steven Anderson

Reputation: 8498

Your problem is related to how you are using this. You refer to this.x within the image.onload = function(). As this is resolved in the current execution context, in this case this will refer to the image being loaded. As you need to refer to this as the Enemy you can make a variable reference to maintain the context of the Enemy:

Enemy.prototype.draw = function(){
  var image = new Image();
  var self = this;
  image.onload = function() {
    Context.context.drawImage(image, self.x, self.y, self.width, self.height);
  };
  image.src = "enemy.png";
}

When you do alert(this.x) you will get the correct value as the scope from where you are calling it is correct. To see this in action add the following code and look at the results in your browser dev tools:

var self = this;
image.onload = function() {
  console.log(this);
  console.log(self);
}  

Upvotes: 2

Lucman Abdulrachman
Lucman Abdulrachman

Reputation: 393

The context under image.onload event is under image not of instance of Enemy.

For you to access x, y, width, and height, you need to store instance to some variable like:

Enemy.prototype.draw = function() {
  var image = new Image();
  var self = this;
  image.onload = function() {
    Context.context.drawImage(image, self.x, self.y, self.width, self.height);
  };
  image.src = "enemy.png";    
}

Upvotes: 0

Related Questions