Brimby
Brimby

Reputation: 922

Javascript objects: how are these two values different?

I'm pretty new to OOP, and I'm having trouble discerning why I am getting different values for the two console logs. The first log gives me the correct height value, the second one which accesses the value through an object property is telling me the height is 0. I can also say that if I run a console log on imageLoader.images[this.sprite], and on player1.height when this.height = imageLoader.images[this.sprite] (so basically I removed the .height property from each value), the first log correctly names the sprite even when it has been dynamically changed, while the second log once again is incorrect and only names the sprite that the object was assigned on creation (from the imageName argument).

As a little bit of background, the constructor is pulling images from the object images from within the object imageLoader, with each actual image contained in a property named after the image's name. I want to have access to each image's height through the height property of each new Thing.

function Thing(imageName) {
    this.sprite = imageName;
    this.height = imageLoader.images[this.sprite].height;
}

var player1 = new Thing ("face_right");

console.log(imageLoader.images[player1.sprite].height);
console.log(player1.height);

Hope that was somewhat clear. Thanks for taking a look.

Upvotes: 1

Views: 59

Answers (1)

nnnnnn
nnnnnn

Reputation: 150070

You don't show any code that would cause the sprite to change, but you seem to be saying you want the player1.height to automatically update to reflect the height of whatever the current sprite is, where the sprite can change dynamically? If so it won't work the way you currently have it because the this.height property you set will just be a primitive number value - it's not a reference to the other object's property. You'd need to add code to change the Thing instance's .height property when the sprite is updated.

Or instead of having a .height property have a .height() method - or perhaps call it .getHeight() as follows:

function Thing(imageName) {
    this.sprite = imageName;
    this.getHeight = function() {
        return imageLoader.images[this.sprite].height;
    }
}

var player1 = new Thing ("face_right");
console.log(player1.getHeight());

Upvotes: 2

Related Questions