任何人都可以解释为什么这不起作用:
var todayDate = new Date();
var todayYear = todayDate.getFullYear();
var User = {
firstName: "John",
lastName: "Doe",
email: "email@email.com",
dob: new Date(85, 1, 1),
userBirthYear: dob.getFullYear(),
age: todayYear - userBirthYear,
url: "http://www.google.com",
bio: "I love pizza",
interests: ["food", "NBA", "movies"]
}
userBirthYear
似乎没有初始化。如果我将对象外部的userBirthYear
作为单独的变量移动,它可以正常工作。
答案 0 :(得分:1)
dob
不是变量,它是User对象的属性。
但是在编译完整个对象之前,你无法直接访问对象属性
你可以这样做;
var User = {
firstName: "John",
lastName: "Doe",
email: "email@email.com",
dob: new Date(85, 1, 1),
age: todayYear - userBirthYear,
url: "http://www.google.com",
bio: "I love pizza",
interests: ["food", "NBA", "movies"]
}
// User object now exists, modify it any way you need
User.userBirthYear = User.dob.getFullYear();