1function Person(dob) {
2 // [1] new Date(dateString)
3 this.birthday = new Date(dob); // transform birthday in date-object
4
5 this.calculateAge = function() {
6 // diff = now (in ms) - birthday (in ms)
7 // diff = age in ms
8 const diff = Date.now() - this.birthday.getTime();
9
10 // [2] new Date(value); -> value = ms since 1970
11 // = do as if person was born in 1970
12 // this works cause we are interested in age, not a year
13 const ageDate = new Date(diff);
14
15 // check: 1989 = 1970 + 19
16 console.log(ageDate.getUTCFullYear()); // 1989
17
18 // age = year if person was born in 1970 (= 1989) - 1970 = 19
19 return Math.abs(ageDate.getUTCFullYear() - 1970);
20 };
21}
22var age =new Person('2000-1-1').calculateAge();
23console.log(age); // 19
24