js class inheritance code example
Example 1: 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 2: override function javascript class
class newArray extends Array{
push(value) {
console.log(`pushed ${value} on to array`)
super.push(value)
}
}
var array = new newArray
array.push('new Value')
Example 3: setting property to method in child class javascript
class Person{
constructor(name,place){
this.name = name;
this.place = place;
}
Full(){
console.log(`I am ${this.name} from ${this.place}`);
}
};
class Student extends Person{
constructor(name,place,age){
super(name,place);
this.age = age;
}
Detail(){
this.area = "Adayar";
console.log(`I'm ${this.name} from ${this.place}, area ${this.area} & I'm ${this.age} years old`);
}
Detailed(){
console.log(`${this.area}`);
}
};
var student1 = new Student("Surya", "Chenai", 25);
student1;
student1.Full();
student1.Detail();
student1.Detailed();
Example 4: 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
});
}