Mozilla intro to OO

by BrownieBoy

HTML

<input type="button" onclick="doAction();" value="doAction()"><br>
<br>
<br>

<input name="TestField" value="" id="TestField"></form>

JavaScript

// define the Person Class

function Person() {}

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

// define the Student class

function Student() {
    // Call the parent constructor
    Person.call(this);
}

// inherit Person
Student.prototype = new Person();

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

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

// add sayGoodBye method
Student.prototype.sayGoodBye = function() {
    console.log('goodBye');
}

function doAction() {
    var student1 = new Student();
    var person1 = new Person();
    student1.sayHello();
    student1.walk();
    student1.sayGoodBye();

    // check inheritance
    console.log(student1 instanceof Person); // true 
    console.log(student1 instanceof Student); // true
    person1.walk(); // true
    Student.prototype.walk = function() {
        console.log("walk ovewritten at Student level");
    };
    person1.walk(); // true
    student1.walk(); // true
}