Skip to content

Instantly share code, notes, and snippets.

@drblue
Last active March 29, 2022 08:54
Show Gist options
  • Save drblue/54606d9e001fc71b2a6a327bc3d3152e to your computer and use it in GitHub Desktop.
Save drblue/54606d9e001fc71b2a6a327bc3d3152e to your computer and use it in GitHub Desktop.
Classes in JavaScript
class Rectangle {
constructor(rooms, jacuzzi, solarPanels = true) {
if (typeof height !== "number") {
throw new Error("Height is not a number")
}
this.height = height
this.width = width
}
area() {
return this.height * this.width
}
circumference() {
return this.height * 2 + this.width * 2
}
}
const myRectangle1 = new Rectangle(10, 20)
console.log("myReactangle1 area", myRectangle1.area())
const myRectangle2 = new Rectangle(15, 25)
console.log("myReactangle1 area", myRectangle2.area())
const notaRectangle = new Rectangle("lol", "cats")
class Animal {
constructor(name) {
this.name = name
}
speak() {
return `${this.name} makes a noise.`
}
}
class Pet extends Animal {
constructor(name) {
super(name)
this.hasOwner = true
}
}
class Dog extends Pet {
constructor(dogname, barkSound = "woff") {
super(dogname)
this.barkSound = barkSound
}
speak() {
return `${this.name} barks: ${this.barkSound}`
}
}
const animal1 = new Animal("Anonymous Animal")
console.log(animal1.speak())
const goodboi1 = new Dog("Good boi 1")
console.log(goodboi1.speak())
const goodboi2 = new Dog("Good boi 2", "aoooooooo")
console.log(goodboi2.speak())
console.log(goodboi2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment