I have a class to create a user, when I add a init() function to the class which should be executed as soon as the class is initialized, it returns a SyntaxError.
I followed this answer but get another SyntaxError
Can anyone tell me what I am doing wrong, I want dob and age to be set on initialisation
JavaScript
x
28
28
1
class User{
2
constructor(name, dob){
3
this.name = name;
4
this.dob = null;
5
this.age = null;
6
}
7
8
setAge(){
9
let currentDate = new Date();
10
let age = currentDate - this.dob;
11
this.age = age;
12
}
13
14
setDob(dob){
15
let dateArray = dob.split('/');
16
let formatedDob = new Date(dateArray[2], dateArray[1]-1, dateArray[0])
17
this.dob = formatedDob
18
}
19
20
init(){
21
setDob(dob);
22
setAge();
23
}
24
25
this.init()
26
};
27
28
const user1 = new User('Garfield', '10/1/1999');
Advertisement
Answer
Alternatively to the other answer, you can call any initialising methods directly in the constructor – that is what the constructor is there to do.
JavaScript
1
6
1
constructor(name, dob){
2
this.name = name;
3
this.setDob(dob);
4
this.setAge();
5
}
6