Mike
Mike

Reputation: 265

Number returning NaN?

I am working with objects with numerous properties and using those properties to draw to canvas. Some properties I am calculating using the others. However, I am hitting an issue!

Basically, I have an object with numerous properties and although when I check the type of data stored in the properties it returns "Number", when I call the property I am getting NaN... and therefore I cannot use this when drawing to the canvas element.

So basically, I have this:

var MasterObject = {
    Object1: {
        width: Number(document.getElementById("width").value),
        height: Number(document.getElementById("height").value),
        border: 65,
        lines: Math.round((this.width - this.border* 2) / 60),
        lineSpace: (this.width - this.border* 2) / this.lines,
        lineSpace1: this.lineSpace
    }
};

The width, height and border properties return "Number" when using "typeof" in console.log() or alert(). When calling these properties I get the number that they store!

Although the property "lines" also returns "Number", when I actually try to call the property it returns "NaN".

The width, height and border, although worked out dynamically, are always a whole integer and I have tried wrapping the "line" property value with Number [i.e. Number(Math.round((this.width - this.border* 2) / 60)) ].

I have also read to try parseInt(), etc, but that is not working either.

I'm sure this is something simple but I can't get my head around what is going on. Why is the type of data returning Number but the actually data is returning NaN... I'm confused!!

Appreciate any help.

Upvotes: 1

Views: 4409

Answers (1)

CDelaney
CDelaney

Reputation: 1248

The context of this is not the object in which you're referencing it. One thing you could do is move your code into functions so it will be the context you desire, and then call the function instead of the property.

var MasterObject = {
    Object1: {
        width: Number(document.getElementById("width").value),
        height: Number(document.getElementById("height").value),
        border: 65,
        lines: function() {
          return Math.round((this.width - this.border* 2) / 60);
        },    
        lineSpace: function() {
          return (this.width - this.border* 2) / this.lines;
        },
        lineSpace1: function() { return this.lineSpace; }
    }
};

document.getElementById('print').innerHTML = MasterObject.Object1.lines();
<input id="width" value="10">
<input id="height" value="15">
<div id="print"></div>

Upvotes: 1

Related Questions