inheritance function js code example
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: 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 3: javascript inherit function
function inherit(c, p) {
Object.defineProperty(c, 'prototype', {
value: Object.assign(c.prototype, p.prototype),
writable: true,
enumerable: false
});
Object.defineProperty(c.prototype, 'constructor', {
value: c,
writable: true,
enumerable: false
});
}
function _inherit(c, ...p) {
p.forEach(item => {
Object.defineProperty(c, 'prototype', {
value: Object.assign(c.prototype, item.prototype),
writable: true,
enumerable: false
});
})
Object.defineProperty(c.prototype, 'constructor', {
value: c,
writable: true,
enumerable: false
});
}