JavaScript Inheritance

One of the big deceptions in JavaScript when coming from other object-oriented languages is that is has classes. Therefore a developer might be puzzled to see a code like this:

  <script type="text/javascript">

	function Vessel(name) {
	   this.name = name;
	}
    Vessel.prototype.canSail = true;
	Vessel.prototype.sail = function() {
	   if (this.canSail)
	       console.log(this.name + " is sailing.");
	}

    var vessel = new Vessel("MyVessel");

    //inherit Vessel
    function Submarine() {
	   Vessel.apply(this, arguments);
	}
    Vessel.prototype = new Vessel();
	
  </script>

In classical object-oriented languages instances are created from classes. JavaScript differs in that aspect as here we have prototype inheritance and no classes are existent. In other words objects inherit from objects.

  <script type="text/javascript">

	var vessel = {
	   canSail: true,
	   canSubmerge = false
 	};

	var submarine = Object.create(vessel);
	submarine.canSubmerge = true;
	console.log(Object.getPrototypeOf(submarine)); //vessel

  </script>

If we try to read a property from the submarine object, the object itself is checked and if property is not found, it goes down the prototype chain checking each prototype object until a first occurrence of the property. The objects are alive and can be altered any time.


  <script type="text/javascript">

	vessel.isLoaded = true;
	console.log(submarine.isLoaded); //true

  </script>

When overriding methods, they can be run from the parent class in the current context in object-oriented languages. In JavaScript we can run any function in any context. Using the call and apply methods which are available on the Function prototype does the job. They provide the possibility to run a method in a specific context passed as a first parameter.

  <script type="text/javascript">

	vessel.load = function(goods) {
	   console.log(goods + " are loaded.");
	};

	submarine.anchor = function(goods) {
           vessel.anchor.call(this, goods);
	};

  </script>
Tags: