0

Could someone help me undertand why I am getting NaN when adding two properties of an object literal together as the definition of a third property?

Here's a code example, and I created a Codepen too.

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

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

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

When I use the constructor to instantiate a new object I get correct math:

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

var objConstructed = new objConstructor();

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

As you can see in the Codepen example I have an object literal, and then the properties are appended to the body in the results frame. I'm also logging 'this' from the Object literal to make sure that the scope is correct and that is is in fact referencing the object.

000
  • 26,951
  • 10
  • 71
  • 101
TristanZimmerman
  • 606
  • 8
  • 12
  • possible duplicate of [Self-references in object literal declarations](http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations) – Quentin Jul 12 '13 at 16:51

2 Answers2

1

When you create the object literal, this is referring to the global scope (where numberOne and numberTwo remain undefined). The function keyword creates the local scope you want.

Joe Beuckman
  • 2,264
  • 2
  • 24
  • 63
1

You can't access the object literal in it's definition, you should create a function for that, check this pen

In it I've defined objectLiteral as:

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

objLiteral.matchStuff(); //130

That way this will be the object, otherwise it'll be window because the object does not exists at that time (and window it's the default scope)

Also, I recommend you search more on this topic, one good (and free) resource is this book

nicosantangelo
  • 13,216
  • 3
  • 33
  • 47
  • Thanks! this really looks like it solved my problem. I knew was missing some fundamental part of how Javascript was functioning, but I couldn't seem to find any info when searching for it. Thanks for the code example and book suggestion too. I passed them both around to my colleagues so they could bask in the learning. – TristanZimmerman Jul 12 '13 at 22:03