JS对象表达式赋值属性返回NaN,如何无需函数添加age属性?
age Property to a JavaScript Object Without Using a Function Great question! Let's break down why your direct expression assignment gave you NaN first, then look at solid solutions to add that age property without relying on a separate function call.
Why Direct Assignment in the Object Literal Returns NaN
When you try to write something like:
var john = { // ... other properties yearOfBirth: 1990, age: 2018 - this.yearOfBirth // Returns NaN };
This fails because during object literal initialization, this does NOT point to the object being created. Instead, this refers to the surrounding execution context (in a browser, that's the global window object). Since window.yearOfBirth doesn't exist, it evaluates to undefined, and 2018 - undefined results in NaN.
Solution 1: Use an ES6 Getter Property
The cleanest way to add a dynamic age property without a function call is to use a getter. Getters are invoked automatically when you access the property, and at that point, this correctly references the object:
var john = { firstName: "John", lastName: "Smith", job: "Teacher", yearOfBirth: 1990, family: ['Jane', 'Mark', 'Bob'], // Getter for age get age() { return 2018 - this.yearOfBirth; } }; console.log(john.age); // Outputs 28
Bonus: If you ever update john.yearOfBirth, accessing john.age will automatically return the new calculated value—no need to re-run a function!
Solution 2: Assign the Property After Object Initialization
If you don't need the age to be dynamic (i.e., it won't change if yearOfBirth updates), you can simply create the object first, then assign age separately. This works because the object is fully initialized, so you can safely reference its properties:
var john = { firstName: "John", lastName: "Smith", job: "Teacher", yearOfBirth: 1990, family: ['Jane', 'Mark', 'Bob'] }; // Assign age after the object exists john.age = 2018 - john.yearOfBirth; console.log(john.age); // Outputs 28
This is straightforward and works in all JavaScript environments, even older ones that don't support ES6 getters.
Wrap-Up
Both methods avoid the need for a separate calculateAge() function call. Use the getter if you want age to stay in sync with yearOfBirth, or post-initialization assignment if you just need a static value.
内容的提问来源于stack exchange,提问作者Gourav Pokharkar

