prototype inheritance in javascript super method 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: override function javascript class

class newArray extends Array{
    push(value) {
        //execute any logic require before pushing value onto array
        console.log(`pushed ${value} on to array`)
        super.push(value)
    }    
}

var array = new newArray

array.push('new Value')

Example 3: 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 4: setting property to method in child class javascript

// setting a new property in child class that extends parent or whatever

//PARENT CLASS
class Person{
  constructor(name,place){
  this.name = name; //property
  this.place = place; //property
  }
  Full(){ //method
    console.log(`I am ${this.name} from ${this.place}`);
  }
};

//CHILD CLASS EXTENDING PARENT
class Student extends Person{
  constructor(name,place,age){
    super(name,place);
    this.age = age; // always call super before accessing ("this")
  }
  Detail(){ //method
    this.area = "Adayar"; //NEW PROPERTY IN our CHILD METHOD
    console.log(`I'm ${this.name} from ${this.place}, area ${this.area} & I'm ${this.age} years old`);
  }
 Detailed(){ //method
    console.log(`${this.area}`); // it can still access in other method inside it's own child class
 }
};

var student1 = new Student("Surya", "Chenai", 25);
student1;
student1.Full();
student1.Detail();
student1.Detailed();