Created
October 18, 2022 22:53
-
-
Save victorabraham/30f8bd482e7a785644975e68c0d5b3c5 to your computer and use it in GitHub Desktop.
Inheritance in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Animal { | |
constructor(name, age) { | |
this.name = name; | |
this.age = age; | |
} | |
eats() { | |
console.log(this.name + ' eats'); | |
} | |
} | |
class Dog extends Animal { | |
constructor(name, age, breed) { | |
super(name, age); | |
this.breed = breed; | |
} | |
logBreed() { | |
console.log(this.name + ' breed is ' + this.breed); | |
} | |
} | |
console.dir(Animal); | |
console.dir(Dog); | |
let cow = new Animal('Passomba', 1); | |
let dober = new Dog('Dober', 2, 'Doberman'); | |
cow.eats(); | |
dober.logBreed(); | |
dober.eats(); | |
console.dir(cow); | |
console.dir(dober); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//PROTOTYPICAL INHERITANCE | |
function Animal(name, age) { | |
this.name = name; | |
this.age = age; | |
} | |
Animal.prototype.eats = function () { | |
console.log(this.name + ' eats'); | |
}; | |
function Dog(name, age, breed) { | |
Animal.call(this, name, age); | |
this.breed = breed; | |
} | |
//Both syntaxes are valid | |
Dog.prototype = Object.create(Animal.prototype); | |
// Dog.prototype = new Animal(); | |
Dog.prototype.logBreed = function () { | |
console.log(this.name + ' breed is ' + this.breed); | |
}; | |
console.dir(Animal); | |
console.dir(Dog); | |
let cow = new Animal('Pasoomba', 1); | |
let dober = new Dog('Dottie', 2, 'Doberman'); | |
console.dir(cow); | |
console.dir(dober); | |
console.log(dober.eats()); | |
console.log(dober.logBreed()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment