質問

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.

役に立ちましたか?

解決

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

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top