数字返回 NaN?

Number returning NaN?

我正在处理具有大量属性的对象,并使用这些属性绘制到 canvas。我正在使用其他属性计算一些属性。但是,我遇到了一个问题!

基本上,我有一个具有许多属性的对象,虽然当我检查存储在属性中的数据类型时,它 returns "Number",当我调用 属性 我我得到 NaN... 因此在绘制到 canvas 元素时我不能使用它。

基本上,我有这个:

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
    }
};

在 console.log() 或 alert() 中使用 "typeof" 时的宽度、高度和边框属性 return "Number"。调用这些属性时,我得到了它们存储的数字!

虽然 属性 "lines" 也 returns "Number",但当我实际尝试调用 属性 时 returns "NaN"。

宽度、高度和边框虽然是动态计算的,但始终是一个整数,我尝试将 "line" 属性 值用数字 [即数字(Math.round((this.width - this.border* 2) / 60)) ].

我也阅读过尝试使用 parseInt() 等,但这也不起作用。

我确定这很简单,但我无法理解正在发生的事情。为什么数据类型是 returning Number 但实际数据是 returning NaN...我很困惑!!

感谢任何帮助。

this 的上下文不是您引用它的对象。您可以做的一件事是将您的代码移动到函数中,这样它 成为您想要的上下文,然后调用该函数而不是 属性.

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>