Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
ES6 Classes are modern syntax for creating constructor functions and prototypes. Same functionality, but cleaner and easier to read!
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log('Hi ' + this.name);
};class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log('Hi ' + this.name);
}
}Creating and using a class
The constructor() method sets up initial properties
class Car {
constructor(make, model, year) {
// Set up properties
this.make = make;
this.model = model;
this.year = year;
this.mileage = 0; // Default value
}
drive(miles) {
this.mileage += miles;
}
}
const car = new Car('Toyota', 'Camry', 2020);
console.log(car.make); // 'Toyota'Setting up initial state
Methods defined in class are automatically added to the prototype (shared by all instances)
class Calculator {
constructor() {
this.result = 0;
}
add(num) {
this.result += num;
return this; // For chaining
}
subtract(num) {
this.result -= num;
return this;
}
getResult() {
return this.result;
}
}
const calc = new Calculator();
calc.add(10).add(5).subtract(3);
console.log(calc.getResult()); // 12Working with instance methods
Use static keyword for utility methods that don't need instance data
class MathHelper {
static add(a, b) {
return a + b;
}
static multiply(a, b) {
return a * b;
}
}
// Call on class, not instance
console.log(MathHelper.add(5, 3)); // 8
console.log(MathHelper.multiply(4, 2)); // 8
// Can't call on instance
const helper = new MathHelper();
// helper.add(5, 3); // Error!Utility methods on the class
Use get and set keywords
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// Getter - access like a property
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
// Setter - set like a property
set fullName(name) {
const [first, last] = name.split(' ');
this.firstName = first;
this.lastName = last;
}
}
const person = new Person('John', 'Doe');
console.log(person.fullName); // 'John Doe'
person.fullName = 'Jane Smith';
console.log(person.firstName); // 'Jane'Computed and controlled properties
class MyClass {
constructor(param1, param2) {
this.property1 = param1;
this.property2 = param2;
}
// Instance method
instanceMethod() {
// uses this.property1, etc.
}
// Static method
static staticMethod() {
// utility function
}
// Getter
get computedProperty() {
return this.property1 + this.property2;
}
// Setter
set computedProperty(value) {
// validation and assignment
}
}