Classes (ES6) in JavaScript
class Foo { constructor() {} }. syntactic sugar over prototypes.
IntermediateObject ProgramsExample 2 of 2
classes-es6.js
1// Class declaration2class Person {3 constructor(name, age) {4 this.name = name;5 this.age = age;6 }78 greet() {9 return `Hello, I'm ${this.name}`;10 }1112 getAge() {13 return this.age;14 }15}1617let person1 = new Person("Alice", 25);18console.log(person1.greet());19console.log("Age:", person1.getAge());2021// Class with inheritance22class Student extends Person {23 constructor(name, age, grade) {24 super(name, age); // Call parent constructor25 this.grade = grade;26 }2728 study() {29 return `${this.name} is studying`;30 }3132 // Override parent method33 greet() {34 return `Hi, I'm ${this.name}, a student`;35 }36}3738let student1 = new Student("Bob", 20, "A");39console.log("\nStudent:");40console.log(student1.greet());41console.log(student1.study());42console.log("Grade:", student1.grade);4344// Static methods45class MathUtils {46 static add(a, b) {47 return a + b;48 }4950 static multiply(a, b) {51 return a * b;52 }53}5455console.log("\nStatic methods:");56console.log("Add:", MathUtils.add(5, 3));57console.log("Multiply:", MathUtils.multiply(5, 3));5859// Getters and Setters60class Circle {61 constructor(radius) {62 this._radius = radius;63 }6465 get radius() {66 return this._radius;67 }6869 set radius(value) {70 if (value > 0) {71 this._radius = value;72 } else {73 throw new Error("Radius must be positive");74 }75 }7677 get area() {78 return Math.PI * this._radius ** 2;79 }80}8182let circle = new Circle(5);83console.log("\nCircle:");84console.log("Radius:", circle.radius);85console.log("Area:", circle.area.toFixed(2));86circle.radius = 10;87console.log("New radius:", circle.radius);88console.log("New area:", circle.area.toFixed(2));
Output
Hello, I'm Alice Age: 25 Student: Hi, I'm Bob, a student Bob is studying Grade: A Static methods: Add: 8 Multiply: 15 Circle: Radius: 5 Area: 78.54 New radius: 10 New area: 314.16
What's going on
constructor runs on new Foo(). Forget new and this is undefined in strict mode.
extends plus super() — skip super and the derived constructor throws.