OO – Inheritance Example

by manu troiani

JavaScript

// Define the Person constructor
function Person(name) {
    this.name = name;
};
// Add a couple of methods to Person.prototype
Person.prototype.walk = function () {
    console.log("I am walking!");
};
Person.prototype.sayHello = function () {
    console.log("Hello, I'm " + this.name + ".");
};

// Define the Student constructor
function Student(name, subject) {
    // Initialize our Student-specific properties
    this.subject = subject;
    // Call the parent constructor function in own context
    Person.call(this, name);
};
// Create a Student.prototype object that inherits from Person.prototype
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;

// Override the "sayHello" method
Student.prototype.sayHello = function () {
    // if we want to still run the parent method, we call it in our context
    Person.prototype.sayHello.call(this);
    console.log("I'm studying " + this.subject + ".");
};
// Add a "sayGoodBye" method
Student.prototype.sayGoodBye = function () {
    console.log("Goodbye!");
};

// Example usage:
var student1 = new Student("Janet", "Applied Physics");
student1.sayHello();
student1.walk();
student1.sayGoodBye();

// Check that instanceof works correctly
console.log(student1);
console.log('I am a Person:', student1 instanceof Person);
console.log('I am a Student:', student1 instanceof Student);