Lucas Penney Lucas Penney - 1 year ago 54
Javascript Question

JavaScript Extending Class

I have a base class:

function Monster() { = 100;

Monster.prototype.growl = function() {

That I want to extend and create another class with:

function Monkey extends Monster() {
this.bananaCount = 5;

Monkey.prototype.eatBanana {
this.bananaCount--;; //Accessing variable from parent class monster
this.growl(); //Accessing function from parent class monster

I've done quite a bit of research and there appears to be many convoluted solutions for doing this in JavaScript. What would be the simplest and most reliable way of accomplishing this in JS?

Answer Source

This MDN document describes extending classes well:

In particular, here is now they handle it:

// define the Person Class
function Person() {}

Person.prototype.walk = function(){
  alert ('I am walking!');
Person.prototype.sayHello = function(){
  alert ('hello');

// define the Student class
function Student() {
  // Call the parent constructor;

// inherit Person
Student.prototype = Object.create(Person.prototype);

// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;

// replace the sayHello method
Student.prototype.sayHello = function(){
  alert('hi, I am a student');

// add sayGoodBye method
Student.prototype.sayGoodBye = function(){

var student1 = new Student();

// check inheritance
alert(student1 instanceof Person); // true 
alert(student1 instanceof Student); // true

Note that Object.create() is unsupported in some older browsers, including IE8:

enter image description here

If you are in the position of needing to support these, the linked MDN document suggests using a polyfill, or the following approximation:

function createObject(proto) {
    function ctor() { }
    ctor.prototype = proto;
    return new ctor();

Using this like Student.prototype = createObject(Person.prototype) is preferable to using new Person() in that it avoids calling the parent's constructor function.