Object Oriented JS
DOM
Document Object Model
Object Literals
Great for modeling one specific thing (encapsulation, property, method):
const ernie = {
animal:'dog',
bark:function(){
console.log('bark');
}
}
ernie.bark();
ernie['bark']();
Classes
Great for modeling one generic thing (uses protypes under the hood, property, method):
class Pet {
constructor(animal, age, breed, sound) {
this.animal = animal;
this.age = age;
this.breed = breed;
this.sound = sound;
}
speak() {
console.log(this.sound);
}
}
const ernie = new Pet('dog', 1, 'pug', 'woof');
ernie.speak()
Getters & Setters
Create properties with dynamic values using getters in JavaScript.
Get: returns a computed value, but is not stored anywhere
Set: allows you to store a variable not set in the constructor
class Pet {
constructor(animal, age, breed, sound) {
this.animal = animal;
this.age = age;
this.breed = breed;
this.sound = sound;
}
get activity() {
const today = new Date();
const hour = today.getHours;
if ( hour > 8 && hour < 20 ) {
return 'Playing';
} else {
return 'Sleeping';
}
}
get owner() {
return this._owner;
}
// naming convention _name
set owner(owner) {
this._owner = owner;
console.log(`setter called: ${this._owner}`)
}
speak() {
console.log(this.sound);
}
}
// some usage
const ernie = new Pet('dog', 1, 'pug', 'woof');
ernie.speak()
ernie.owner = "Joe";
ernie.activity
Home