Inheritance - JavaScript

by lshettyl

HTML

<h2>Explain inheritance in JavaScript.</h2>
<p>
 As an object-oriented, class-free scripting language, JavaScript uses prototypal or differential inheritance instead of the classical inheritance you will find in class-based programming languages like Java and C#. In programming, differential inheritance is when one object gains the properties of another object.

In basic terms, differential inheritance works by assuming objects are all derivatives of other, generic objects, setting these objects apart based on their differences.

    <br/>Example:   
</p>
<h4 id="result"></h4>

JavaScript

var display = document.getElementById('result');
var results = null;
// Create and define Adult.
function Adult() {}
Adult.prototype.speak = function(){
  return 'I am an adult!';
};
Adult.prototype.workDay= function(){
  return 'I have to go to work.';
};

// Create and define Student.
function Student() {
  // Call the Adult function.
  Adult.call(this);
}

// Tell Student to inherit Adult.
Student.prototype = new Adult();

Student.prototype.constructor = Student;

// Change the workDay method.
Student.prototype.workDay= function(){
  return 'I have to do my homework.';
}

// add speakGoodbye method
Student.prototype.speakGoodbye= function(){
  return 'I am going to the library. Goodbye.';
}

var studentA = new Student();
results = studentA.workDay();
results += '<br/>';
results += studentA.speak();
results += '<br/>';
results += studentA.speakGoodbye();
results += '<br/>';

// To check for inheritance:
results += studentA instanceof Adult;
// Returns true.
results += '<br/>';
results += studentA instanceof Student;
// Returns true.
results += '<br/>';
display.innerHTML = results;