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

Show parent comment

1

u/[deleted] May 16 '22 edited May 16 '22

Thanks for the elaborated explanation I'm gonna save it for sure,

can I ask one more stupid question,I don't want to make another post about it.

Ok so,

This is my module(user.js):

 function UserLogin(name,password) {
this.name = name;
this.password = password;
};

function UserData(age,gender) { 
    this.age = age; 
    this.gender = gender;
    this.say = ()=>{
        console.log("Your age is: "+this.age);
        console.log("Your gender is: "+this.gender);
    }
};

module.exports.Login = UserLogin; 
module.exports.Data = UserData;

and this is my app.js

const User = require(./path/user)
const user1 = {
login:User.Login("Adam",8521);
data:User.Data(18,"male");
}
console.log(JSON.stringify(u1)); //returning {} 
console.log("Login: "+ u1.login); //undefined 
console.log("Data: "+ u1.data); //undfined

The editor or console are not throwing any error so what am I doing wrong?

How can I use the say() method inside "Data" in user1?

5

u/senocular May 16 '22

Despite the syntax issues (which are presumably just typos) the main problem is that you're not using new to create your instances. This is one of things mentioned in the safety bullet point that class syntax protects you from. If you had used class you would have gotten an error informing you that you were missing new.