Object Literals Aren’t Enough
const ernie = {
animal: 'dog',
age: '1',
breed: 'pug',
bark: function(){
console.log('Woof!');
}
}
const vera = {
animal: 'dog',
age: 8,
breed: 'Border Collie',
bark: function(){
console.log('Woof!');
}
}
const scofield = {
animal: 'dog',
age: 6,
breed: 'Doberman',
bark: function(){
console.log('Woof!');
}
}
const edel = {
animal: 'dog',
age: 7,
breed: 'German Shorthaired Pointer',
bark: function(){
console.log('Woof!');
}
}
As you can see, using object literals isn’t always feasible.
Classes are a more robust option for generating and working with objects.
Class
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!');
const vera = new Pet('dog', 8, 'Border Collie', 'Woof!');
const scofield = new Pet('dog', 6, 'Doberman', 'Woof!');
const edel = new Pet('dog', 7, 'German Shorthaired Pointer', 'Woof!');
ernie.speak();
vera.speak();