A guide on immediately invoking a method when a class is initialized in JavaScript

I'm having some trouble with a class I created to handle user information. When I try to add an init() function to the class so that it runs as soon as the class is initialized, I keep getting a SyntaxError.

I've tried following the advice from this post, but I end up with another SyntaxError.

Could someone please point out what I might be doing wrong? My goal is to have dob and age set upon initialization.

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

Answer №1

Instead of following the previous answer, you have the option to execute any initialization methods directly within the constructor function - after all, that's precisely what the constructor is designed for.

constructor(firstName, lastName){
        this.firstName = firstName;
        this.setLastName(lastName);
        this.calculateAge();
}

Answer №2

Indeed, the answer lies within the constructor function. To streamline your code, eliminate the null value and modify it as follows:

constructor(title, date){
    this.title = title;
    this.setDate(date);
    this.calculateYears();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Configuring React classes for compilation within Play

After incorporating a basic React class into my Play project at /app/assets/js: var Question = React.createClass({ render: function() { return (<div> <p>{this.props.content}</p> <br> <p>{this.props.an ...

Should mutators be encapsulated within a class contained in a JS Module for better code organization and maintainability?

In order to maximize functionality of our new product using JavaScript, we have implemented an Authentication module that manages a tokenPromise which is updated upon user logins or token refreshes. It seems imperative to allow for mutation in this process ...

Exploring the versatility of MaterialUI: Combining useStyle() with regular classes in the same className declaration

I am currently incorporating MaterialUI into my React Project and I am trying to combine the use of useStyle() classes with a regular class in one of my components. Here is an example from my code: ... const useStyles = makeStyles(theme => ({ fontS ...

Using Rails: How to invoke a function in the asset pipeline from a JS response?

In one of the JavaScript files I am working with, I have defined an object and a function: chosen.coffee Foo = do_this: -> $('.slider').slider() $ -> Foo.do_this() This code initializes JQueryUI to turn a specific div into a ...

Ways to render component solely based on the alteration of the class props

In my ReactJS project, I am fetching JSON data from a RESTful Django host and using it to create a table with filters. Here is my Table class: class MainTable extends React.Component { constructor(props) { super(props); this.state = { res ...

When attempting to call a recursive method in Vue with a changing `this` object, an error is thrown: "RangeError: Maximum call stack size exceeded"

Update integrate codePen into the project. https://codepen.io/jiaxi0331/pen/xxVZBMz Description encountered an issue while trying to call the parent method recursively Code export default { methods: { dispatch(componentName, event, value) { ...

The calculator is experiencing issues with JavaScript functionality

Having some trouble developing a calculator using HTML5, CSS, and JavaScript. After passing my HTML and CSS through validators successfully, I encountered issues when adding JavaScript functions to enable the functionality of the buttons on the calculator. ...

Utilizing Isotope JS on your Wordpress website

I'm in the process of integrating the .js plugin, Isotope, into my Wordpress installation. It should be positioned at the bottom of this page: To achieve this, I am referring to an example on codepen: https://codepen.io/desandro/pen/mEinp The script ...

Utilizing AJAX in Datatables- Effortlessly sharing a URL link to a designated page

I've recently encountered an issue while using Datatables and AJAX to retrieve data from my Rails server. The problem arises when I try to share a specific page (let's say page 2) with another user who is also using Datatables. Due to the paginat ...

Move the box upwards and change it to grayscale when hovering over the image, then reverse the effect when the hover

As I hover over the image, my goal is to make a gray box appear at the bottom and smoothly slide up. While it slides up, everything it covers should turn grayscale. When I move my mouse away from the image, I want the gray box to slide back down and remove ...

JQuery enables nested sorting functionality

I need to enable the sortable feature specifically for the charts. Index.cshmtml <div id="sortable" class="col-lg-9"> <div class="col-lg-12 col-md-12 padding hidden" id=@($"chartNumber{Model.Charts[ ...

After using JSON.parse(), backslashes are still present

Recently Updated: Received server data: var receivedData = { "files":[ { "filename": "29f96b40-cca8-11e2-9f83-1561fd356a40.png", "cdnUri":"https://abc.s3.amazonaws.com/" ...

Initialization of webix combo options values in HTML code

Currently, I am working with the Webix UI framework and I am trying to achieve something similar to: <div view="combo" options="fruit"></div> This is what I have in my JavaScript file: $scope.fruit =[{id:1, value: "Apple"}, {id:2, value: "Ba ...

Tips on handling a Vue computed property

I am struggling to dispatch an object that is created within a computed property in vue.js. Being fairly new to this framework, I can't seem to make it work. My goal is to dispatch the object named "updateObject" to the vuex-store. I have tried using ...

Dynamically indicate the destination for AJAX success feedback across various forms

Here are a couple of inquiries: Is there a way to incorporate a second form on the same page and dynamically handle each form based on which submit button is clicked? Let's say I have several forms on one page. How can I alter the output destina ...

Can pins be added or removed from a location plan (image or vector) using either Javascript or the DevExpress library?

At the factory where I am employed, there are close to 1000 cameras in operation. I have requested to have the locations of these cameras marked on a non-geographical map of the factory. By simply clicking on one of the camera icons, it should be possible ...

Having trouble retrieving data passed between functions

One of my Vue components looks like this: import '../forms/form.js' import '../forms/errors.js' export default{ data(){ return{ form: new NewForm({ email: '&apos ...

Steps to transforming a standard array into a multidimensional array

I have a JSON array that is generated after submitting a form using the formSerialize function. Here is an example of how the array looks: [ {"name":"client_management-testmonitoring","value":"0"}, {"name":"client_operations-testmonitoring","v ...

Problem with using puppeteer to interact with a dropdown menu

I have a project in which I am utilizing puppeteer to create a bot that can automatically check for my college homework assignments. The problem I am encountering is that when the bot tries to click on a dropdown menu, it fails and I receive an error messa ...

Building Dynamic Columns within a react.js Environment

Can anyone help me with creating a dynamic column in react.js? I've already managed to do it with static columns, but now I want to make them dynamic. Take a look at my code below and please provide suggestions. import React from 'react'; i ...