Week 7 Lesson 6 Video7.5: Object Inheritance - the Basics

by Lucille Kenney

HTML

<h3>Video 7.5: Object Inheritance - the Basics</h3>
<b>Open your console to see the output of this code</b>

JavaScript

// my base object type: Person

/* https://www.youtube.com/watch?v=PJqVlNKVm4o  */

function Person(){
    this.species = 'homo sapiens';
}
Person.prototype.getFullName = function(){
        return this.fname + " " + this.lname;
}

function Student(fname, lname){
    var records = [ {"assignment": "assignment1", "points": 10 }];

    this.fname = fname;
    this.lname = lname;
    
    // add record modifies a private variable  (records), so must
    // live inside the object, not its prototype
    this.addRecord = function(r){
        if(r){
            records.push(r);
        }
    }
    this.totalPoints = function(){
        var total = 0;
        records.forEach(function(record){
            total += record.points;
        });
        return total;
    }
}
/// here's where we make Student inherit from Person
Student.prototype = new Person();

// adding more to the Student prototype
Student.prototype.getInfo = function(){
    return this.getFullName() + " has " + this.totalPoints() + " points.";
};

// I can redefine the toString() method of this object type.
// Otherwise, it would just use Javascript's generic Object.toString()
Student.prototype.toString= function(){
    return this.getInfo();
}

var s = new Student("Excellent", "Student");
console.log(s.getFullName());
s.addRecord( {"assignment" : "assignment2", "points" : 25} );
console.log(s.getInfo());
console.log("this is " + s);

/// telling the difference between inherited vs. local properties
for (var key in s){
    if (s.hasOwnProperty(key)) {
        console.log(key + " value is " + s[key] + "NATIVE");
    }else{
        console.log(key + " value is " + s[key] + "FROM PROTOTYPE");
    }
}


var t = new Student("Tom", "Student");
console.log(t.getFullName() + " is a " + t.species);