Example 1: prototype inheritance javascript
function Animal (name, energy) {
this.name = name
this.energy = energy
}
Animal.prototype.eat = function (amount) {
console.log(`${this.name} is eating.`)
this.energy += amount
}
Animal.prototype.sleep = function (length) {
console.log(`${this.name} is sleeping.`)
this.energy += length
}
Animal.prototype.play = function (length) {
console.log(`${this.name} is playing.`)
this.energy -= length
}
function Dog (name, energy, breed) {
Animal.call(this, name, energy)
this.breed = breed
}
Dog.prototype = Object.create(Animal.prototype)
Dog.prototype.bark = function () {
console.log('Woof Woof!')
this.energy -= .1
}
const charlie = new Dog('Charlie', 10, 'Goldendoodle')
console.log(charlie.constructor)
Example 2: javascript class inheritance
class Mammal {
constructor(name) {
this.name = name;
}
eats() {
return `${this.name} eats Food`;
}
}
class Dog extends Mammal {
constructor(name, owner) {
super(name);
this.owner = owner;
}
eats() {
return `${this.name} eats Chicken`;
}
}
let myDog = new Dog("Spot", "John");
console.log(myDog.eats());
Example 3: inheritance in javascript
class Animal {
constructor(name, weight) {
this.name = name;
this.weight = weight;
}
eat() {
return `${this.name} is eating!`;
}
sleep() {
return `${this.name} is going to sleep!`;
}
wakeUp() {
return `${this.name} is waking up!`;
}
}
class Gorilla extends Animal {
constructor(name, weight) {
super(name, weight);
}
climbTrees() {
return `${this.name} is climbing trees!`;
}
poundChest() {
return `${this.name} is pounding its chest!`;
}
showVigour() {
return `${super.eat()} ${this.poundChest()}`;
}
dailyRoutine() {
return `${super.wakeUp()} ${this.poundChest()} ${super.eat()} ${super.sleep()}`;
}
}
function display(content) {
console.log(content);
}
const gorilla = new Gorilla('George', '160Kg');
display(gorilla.poundChest());
display(gorilla.sleep());
display(gorilla.showVigour());
display(gorilla.dailyRoutine());
Example 4: javascript prototype inheritance example
function Person(first, last, age, gender, interests) {
this.name = {
first,
last
};
this.age = age;
this.gender = gender;
this.interests = interests;
};
function Teacher(first, last, age, gender, interests, subject) {
Person.call(this, first, last, age, gender, interests);
this.subject = subject;
}
Example 5: javascript inheritance
function Teacher(first, last, age, gender, interests, subject) {
Person.call(this, first, last, age, gender, interests);
this.subject = subject;
}
Example 6: javascript inheritance
class Animal {
null
}
class tiger extends Animal {
null }