在Object Literal中添加属性会生成NaN

时间:2013-07-12 16:42:47

标签: javascript javascript-objects object-literal

有人可以帮我解决为什么在将对象文字的两个属性一起添加为第三个属性的定义时我得到NaN?

这是一个代码示例,我也创建了一个Codepen。

http://codepen.io/Tristan-zimmerman/pen/cvJFE

objLiteral = {
 numberOne : 50,
 numberTwo : 80,
 mathStuff : this.numberOne + this.numberTwo,
};

console.log(objLiteral.mathStuff);
//Logs NaN.

当我使用构造函数实例化一个新对象时,我得到了正确的数学:

function objConstructor () {
  this.numberOne = 50;
  this.numberTwo = 80;
  this.mathStuff = this.numberOne + this.numberTwo;
}

var objConstructed = new objConstructor();

console.log(objConstructed.mathStuff);
//Logs 130.

正如你在Codepen示例中看到的,我有一个对象文字,然后属性被附加到结果框架中的主体。我还从Object文字中记录'this',以确保范围正确,实际上是引用对象。

2 个答案:

答案 0 :(得分:1)

创建对象文字时,this指的是全局范围(其中numberOnenumberTwo未定义)。 function关键字会创建所需的本地范围。

答案 1 :(得分:1)

你不能在它的定义中访问对象文字,你应该为它创建一个函数,check this pen

在其中我将objectLiteral定义为:

objLiteral = {
 numberOne : 50,
 numberTwo : 80,
 mathStuff : function() {
    return this.numberOne + this.numberTwo;
 }
};

objLiteral.matchStuff(); //130

那样this将是对象,否则它将是window,因为那时对象不存在(并且窗口是默认范围)

此外,我建议您更多地搜索此主题,一个好的(和免费的)资源is this book