Skip to content

Instantly share code, notes, and snippets.

@cchoi12
Last active April 13, 2018 22:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cchoi12/9144d3d541f7103b9b1c3612b32980da to your computer and use it in GitHub Desktop.
Save cchoi12/9144d3d541f7103b9b1c3612b32980da to your computer and use it in GitHub Desktop.
Read further in prototypes and saw ES6 classes. A lot of syntactic sugar but the concepts are identical.
class Dog {
constructor(name, age) {
this.name = name
this.age = age
}
fetch(obj) {
return `Yo ${this.name}, go fetch the ${obj}`
}
}
class Breed extends Dog {
constructor(name, age, breedName, color, mixed) {
super(name, age)
this.breedName = breedName
this.color = color
this.mixed = Boolean(mixed)
}
description() {
return `${this.name} is a ${this.age} year old ${this.color} ${this.breedName}`
}
mixedBreed() {
return this.mixed
}
static breedOf() {
return 'This is a class that inherits from Dog. This is a class method and cannot be used on instantiated Dog/Breeds(new Dog / new Breed)'
}
}
const boringDog = new Dog('Bob', 2)
console.log(boringDog); // Dog { name: 'Bob', age: 2 }
console.log(boringDog.fetch('stick')); // Yo Bob, go fetch the stick.
console.log(boringDog.description()); // Won't work, methods that are scoped in the subclass(Breed < Dog) will only work with instances of 'Breed'.
const ava = new Breed('Ava', 8, 'Border Collie', 'Black/White', false)
console.log(ava); // Breed { name: 'Ava', age: 8, breedName: 'Border Collie', color: 'Black/White', mixed: false }
console.log(ava.fetch('newspaper')); // Yo Ava, go fetch the newspaper.
console.log(ava.description()); // Ava is a 8 year old Black/White Border Collie.
console.log(ava.constructor.name); // Breed
console.log(ava.mixedBreed()); // False
console.log(Breed.breedOf()); // This is a class that inherits from Dog. This is a class method and cannot be used on instantiated Dog/Breeds(new Dog / new Breed)
console.log(Dog.breedOf()); // Won't work, will only work on the scoped class.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment