class Car {
constructor(brand, type) {
this.brand = brand;
this.type = type;
}
}
const dodgeChallenger = new Car('Dodge', 'Challenger');
const chevySilverado = new Car('Chevy', 'Silverado');
console.log(chevySilverado.type); // "Silverado"
Classes are templates used to create objects.
class - keyword to define classes, named with first-letter capitalization.
constructor() - method called every time it creates a new instance of a class.
this - refers to an instance to that class.
new - used to create a new instance of a class. Variable name will equal the object name, and entered values will equal key: value pairs.
class Animal {
constructor(name) {
this._name = name;
this._behavior = 0;
}
get name() {
return this._name;
}
incrementBehavior() {
this._behavior++;
}
}
class Cat extends Animal {
constructor(name, usesLitter) {
super(name);
this._usesLitter = usesLitter;
}
}
const Kiki = new Cat("Kiki", true);
console.log(Kiki.name); // "Kiki"
Kiki.incrementBehavior();
Kiki.incrementBehavior();
console.log(Kiki._behavior); // 2
Classes can get properties and methods from other classes using extends/super.
extends - used to make a subclass from a parent class.
super - used to call the constructor from the parent class your extending from.
class Dog {
constructor() {
this._behavior = 0;
}
get behavior() {
return this._behavior;
}
incrementBehavior() {
this._behavior++;
}
}
let nikko = new Dog(); // Create dog named Nikko
nikko.incrementBehavior(); // Add 1 to nikko instance's behavior
console.log(nikko.behavior); // call get method to get behavior value, logs 1
Methods are basically functions that can be called and execute code.
class Animal {
constructor(name) {
this._name = name;
this._behavior = 0;
}
static generateName() {
const names = ['Roofus', 'Spike', 'Buffy', 'Willow', 'Tara'];
const randomNumber = Math.floor(Math.random()*5);
return names[randomNumber];
}
}
Animal.generateName()
Sometimes you will want a class to have methods that aren’t available in individual instances, but that you can call directly from the class.
class Dog {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
}
let nikko = new Dog('Nikko'); // Create dog named Nikko
console.log(nikko.name); // logs Nikko
Keyword to identify getter methods, nothing special just return values given from the object. Keyword used to identify its use.
class Dog {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
set changeName(newName) {
this._name = newName;
}
}
let nikko = new Dog('Nikko'); // Create dog named Nikko
console.log(nikko.name); // logs Nikko
nikko.changeName = "Bailey";
console.log(nikko.name); // logs Bailey
Setter methods take in a parameter and reassign values of existing properties.