How to specialize a Javascript class?-Collection of common programming errors

I was playing with JavaScript class inheritance (I am using node.js). I get “undefined” values for instances of the child class. Here my example:

I define a Squirrel class and I want to specialize this class in a KillerSquirrel child class. I want create instances of both the Squirrel and the KillerSquirrel classes.

function Squirrel(name, color) {
        this.name = name;
        this.color = color;
        console.log("A new " + this.color + " squirrel named " + this.name + " is born!!!");
    };

    // add a new method called speak()
    Squirrel.prototype.speak = function(text) {
        console.log(this.name + " squirrel says: '" + text + "'");
    };

    // specialize the Squirrel class by creating a new KillerSquirrel constructor 
    function KillerSquirrel(name, color) {    
      this.soul = 'very bad';
      console.log("Bhrrr ... a new " + this.color + " killer squirrel named " + this.name + " is born!!!");
    }  
    KillerSquirrel.prototype.__proto__ = Squirrel.prototype;

    // add kill method  
    KillerSquirrel.prototype.kill = function(obj){  
      console.log(this.name + " squirrel killed " + obj.name + " squirrel"); 
    }

    // replace the speak() method  
    KillerSquirrel.prototype.speak = function(text) {
                       console.log(this.name + " squirrel says: 'Grhhh! " + text + "' Grhhh!");
    };

    var squirrel = new Squirrel("Gummy", "brown");
    squirrel.speak("My name is " + squirrel.name);
    var killer = new KillerSquirrel("Mr.Hide", "black");
    killer.speak("My name is " + killer.name);

I create a squirrel instance of Squirrel using its constructor and passing some values to the constructor and this works as expected. When I try to create an instance of child class KillerSquirrel using its constructor and passing some values to it, the killer squirrel instance has “undefined properties”.

see:

$ node killersquirrel.js
A new brown squirrel named Gummy is born!!!
Gummy squirrel says: 'My name is Gummy'
Bhrrr ... a new undefined killer squirrel named undefined is born!!!
undefined squirrel says: 'Grhhh! My name is undefined' Grhhh!
  1. Subclass constructor should call superclass constructor manually by special construct (apply or call), like this:

    function KillerSquirrel(name, color) {
      Squirrel.apply(this, arguments);    
      this.soul = 'very bad';
      console.log("Bhrrr ... a new " + this.color + " killer squirrel named " + this.name + " is born!!!");
    }  
    

    or

    function KillerSquirrel(name, color) {
      Squirrel.call(this, name, color);    
      this.soul = 'very bad';
      console.log("Bhrrr ... a new " + this.color + " killer squirrel named " + this.name + " is born!!!");
    }  
    

    though for this case (when the arguments are the same) the first form is preferred.

Originally posted 2013-11-09 23:12:21.