Organizing programs
How to use JavaScript Classes
Learn how to use JavaScript classes introduced in ES6, from defining a constructor and methods to creating objects with new and inheritance using extends.
ES2015 added a class syntax on top of JavaScript’s existing prototype model. Under the hood nothing magical changed: objects still inherit through prototypes. The syntax just looks closer to class-based languages like Java or Python.
A class definition
class Person {
constructor(name) {
this.name = name
}
hello() {
return 'Hello, I am ' + this.name + '.'
}
}
Use new Person('Flavio') to create an instance. The constructor runs with whatever arguments you pass.
Methods like hello() live on the prototype and are shared by all instances:
const flavio = new Person('Flavio')
flavio.hello()
Class inheritance
A class can extend another with extends:
class Programmer extends Person {
hello() {
return super.hello() + ' I am a programmer.'
}
}
const flavio = new Programmer('Flavio')
flavio.hello()
This prints _Hello, I am Flavio. I am a programmer._
If a subclass defines a method with the same name as a parent method, the subclass version wins. Call super.method() to reach the parent implementation.
Initialize instance fields in the constructor. Classes do not declare class fields separately in this basic form.
Static methods
Static methods belong to the class, not to instances:
class Person {
static genericHello() {
return 'Hello'
}
}
Person.genericHello() //Hello
Private methods
Prefix a method or a field with # to make it private. Only code inside the class can reach it:
class Person {
#greeting = 'Hello'
hello() {
return this.#format()
}
#format() {
return `${this.#greeting}, I am ${this.name}`
}
}
Calling new Person('Flavio').#format() from outside the class is a syntax error, not a runtime one. The browser refuses to run the file. There is no protected keyword in JavaScript: a member is either public or private to the class body.
Getters and setters
Prefix a method with get or set to control property access:
class Person {
constructor(name) {
this._name = name
}
set name(value) {
this._name = value
}
get name() {
return this._name
}
}
Getter only: reads work, writes outside the constructor are ignored.
Getter without setter: same read-only behavior from the outside.
Setter without getter: you can assign but not read the property from outside.
Getters and setters help when you want validation, logging, or a computed value on access.
Run new Programmer('Flavio').hello() in the console to see inheritance and super in one line of output.
Static methods belong to the class; instance methods belong to each object created with new.
Lesson completed