prototype inheritance javascript 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: 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 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
        });
    }
// Or if you want multiple inheritance

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
        });
    }

Tags:

Misc Example