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

Time:08-17

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');

CodePudding user response:

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();
}

CodePudding user response:

Yes, answer is in the constructor - so to simplify the code, take out the null in your code and re-write:

constructor(name, dob){
    this.name = name;
    this.setDob(dob);
    this.setAge();
}
  • Related