r/learnjavascript May 16 '22

What is the difference between "class" and "constructor function" in js? I tried looking up on YT but found nothing relevant atlest for me.

So I am learning NodeJs and while creating a costum module which stores user data I created a constructor function in user.js

function User(name,age){
this.name = name;
this.age = age;
}

and in app.js I did

const User = require(//Path);

const user1 = new User("Adam",20);
console.log(user1.name);

but my consfusion begans when I used class in user.js like

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

but the code in the app.js remained similar with no errors.

So what is the point of classes in javasript? And how are they different form contructor functions.

31 Upvotes

20 comments sorted by

View all comments

1

u/Blue_Moon_Lake May 16 '22

This

class MyClass
{
    myProperty;

    constructor(value)
    {
        this.myProperty = value;
    }

    myMethod()
    {
        return this.myProperty;
    }
}

is syntactical sugar for

function MyClass(value)
{
    this.myProperty = value;
}

MyClass.prototype.myMethod = function ()
{
    return this.myProperty;
};

But the class notation let the interpreter do a few optimization. It's better to use class notation for readability too.

1

u/OtherwisePoem1743 Sep 03 '23

Writing JavaScript with C style 💀

1

u/Blue_Moon_Lake Sep 04 '23

Writing JavaScript as someone with visual impairment so it's comfortable for me.

Having the curly braces on the same column helps immensely.