<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);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.