JavaScript Class Basic Syntax
JavaScript classes are a modern way to create objects and implement prototypal inheritance in an easy-to-read syntax. They were introduced in ES6 (ECMAScript 2015) and provide a more structured way to define objects compared to constructor functions.
🔹 Basic Class Syntax
A class in JavaScript is created using the class
keyword.
✅ Example: Creating a Class
✔ The constructor()
method initializes properties.
✔ sayHello()
is a method shared across all instances.
🔹 Class Properties
✅ Instance Properties (Defined in Constructor)
✅ Class Fields (Public & Private)
JavaScript now supports class fields, including public and private properties.
✔ Public fields can be accessed anywhere.
✔ Private fields (#
) can only be used inside the class.
🔹 Getters & Setters
We can use getters and setters to control property access.
✅ Example: Using Getters & Setters
✔ The get
method retrieves data.
✔ The set
method validates before assigning values.
🔹 Static Methods (Class-Level Methods)
Static methods belong to the class itself instead of an instance.
✅ Example: Using static
Methods
✔ No need to create an instance to use add()
.
🔹 Class Inheritance (extends
& super
)
A class can inherit from another class using extends
.
✅ Example: Inheriting from a Class
✔ super(name)
calls the parent class constructor.
✔ Dog
overrides the makeSound()
method.
🎯 Summary
✔ Classes provide a clean way to define objects.
✔ Constructor initializes properties when creating an instance.
✔ Class fields can be public or private (#
).
✔ Getters & Setters allow controlled property access.
✔ Static methods belong to the class itself.
✔ extends
& super
enable class inheritance.
🚀 Want more examples? Let me know! 😊