🧠Why class Syntax?
Before ES6 (ECMAScript 2015), JavaScript used constructor functions and prototypes for object creation and inheritance (Which you can learn in Advanced Javascript Course). ES6 introduced the class syntax to make this simpler, cleaner, and more familiar to developers from other OOP languages like Java, C++, etc.
Under the hood, JavaScript classes still use prototypes, but the class syntax makes code easier to read and write.
Syntax :
class ClassName {
constructor(parameters) {
// Initialization code
}
method1() {
// Method code
}
method2() {
// Method code
}
}Example :
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log("Hello, my name is " + this.name);
}
}
const p1 = new Person("Codeveda");
p1.greet(); // Output: Hello, my name is Codeveda🧾 Explanation:
constructor()is automatically called when a new object is created usingnew Person()greet()is a method attached to the prototype(.prototype)of the classp1is an instance ofPerson
❗️Important Points:
Only things that belong to each object individually, like: properties, default values and data passed from outside are put inside constructor.
Methods defined outside constructor go to the prototype, not duplicated.
✅ If greet was inside constructor:
constructor(name) {
this.name = name;
this.greet = function() {
console.log("Hello, my name is " + this.name);
}
}❌ This creates a new function every time for each instance → more memory usage