0

I am written the following code and able to accomplish same output using any of the two approaches. I am little confused and need to understand when should I create a class and when when should I create a function in NodeJs?

//Approach 1
class User {
    constructor() {
        this.name = "John";
        this.age = 30;
    }
    getName() {
        return this.name;
    }
}
let user = new User();
console.log(user.getName());

//Approach 2
let userNew = function () {
    this.name = "Mike";
    this.age = 32;
    this.getName = function () {
    return this.name;
    };
};

let user2 = new userNew();
console.log(user2.getName());
meallhour
  • 13,921
  • 21
  • 60
  • 117
  • 1
    That's two different ways of writing a "class", one using new ES6 syntactic sugar. – jonrsharpe Mar 27 '20 at 16:53
  • 1
    Does this answer your question? [What is the difference between prototype-based class syntax and class syntax in JavaScript?](https://stackoverflow.com/questions/49643582/what-is-the-difference-between-prototype-based-class-syntax-and-class-syntax-in) – VLAZ Mar 27 '20 at 16:56
  • 1
    The ES6 approach is mostly just sugar, but lets you do a lot of neat things more succinctly, such as static methods, getters & setters, and inheritance through the `extends` keyword. It's also more readable to me as it's consistent with other object-oriented languages. – Klaycon Mar 27 '20 at 16:56

1 Answers1

0

I have written classes when I have to deal with data state, for example when I have functions that need to share or update some state (developing forms) but for the other cases, I like to code functions. I feel that depends on situation and preference, what is easy or better to you code it? What do you like to achieve?