Class (JavaScript)
A class is a template for creating objects with shared properties and methods. The class keyword gives JavaScript a clean syntax for object-oriented programming.
JavaScript
A constructor sets up each new instance, and methods defined in the class are shared by all instances. Use the new keyword to create an object from a class.
Classes support inheritance with extends and super, building on JavaScript's prototype system.
Syntax
class Name { constructor() { ... } method() { ... } }Examples
JavaScript
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return this.name + " makes a sound";
}
}
console.log(new Animal("Cat").speak());Output:
Cat makes a sound