Skip to content
Advertisement

How to call a method as soon as a class is initialized in JavaScript

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

class User{
    constructor(name, dob){
        this.name = name;
        this.dob = null;
        this.age = null;
    }

    setAge(){
        let currentDate = new Date();
        let age = currentDate - this.dob;
        this.age = age;
    }

    setDob(dob){
        let dateArray = dob.split('/');
        let formatedDob = new Date(dateArray[2], dateArray[1]-1, dateArray[0])
        this.dob = formatedDob
    }

    init(){
        setDob(dob);
        setAge();
    }

    this.init()
};

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.

constructor(name, dob){
        this.name = name;
        this.setDob(dob);
        this.setAge();
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement