Lesson Plan
Prototypes and Inheritance in Javascript

Wed 27 Jan 2016
Last Christmas...
A Christmas Bell in Javascript
/* Currently */

// Create individual bells
var bell01 = {name:"Bell 01"};
var bell02 = {name:"Bell 02"};

// Let's add ribbons!
bell01.ribbonColor = "red";
bell02.ribbonColor = "red";
/* With prototypes */

// A constructor for bells - convenient!
function bell(name) {
    this.name = name;
}

// Create individual bells
var bell01 = new bell("Bell 01");
var bell02 = new bell("Bell 02");

// Let's add ribbons!
bell.prototype.ribbonColor = "red";
Inheritance
console.log(bell01.toString()); // [object Object]

bell01 >> bell.prototype >> Object.prototype
// Override the toString() method from Object prototype, using a callback
bell.prototype.toString = function () {
    return "I am a bell and my name is " + this.name + ".";
}

console.log(bell01.toString()); // I am a bell and my name is Bell 01.

Practice Time!

// Global function which is used to "construct" the individual bells - constructor
function bell(name) {
    this.name = name;
}

// Add properties and methods to prototype which individual bells will inherit
bell.prototype.ribbonColor = "red";
bell.prototype.toString = function () {
    return "I am a bell and my name is " + this.name + ".";
}

// Create individual bells
var bell01 = new bell("Bell 01");
var bell02 = new bell("Bell 02");
  1. Implement lightUp method for all bells,
    ie. bell01.lightUp() outputs to console
  2. Fix easy misuse of current constructor,
    ie. var cowBell = new bell("Cow Bell").
  3. Set ribbon color when creating the individual bells

Assessment

1. Implement lightUp method for all bells
// Add method to bell prototype which all bells will inherit
bell.prototype.lightUp = function () {
    console.log(this.name + " has lighted up!");
}

bell01.lightUp(); // Bell 01 has lighted up!
bell02.lightUp(); // Bell 02 has lighted up!
2. Fix easy misuse of current constructor
// Use namespace to organize application code
var ChristmasBell = function (name) {
    this.name = name;
}

// Create individual bells
var bell01 = new ChristmasBell("Bell 01");
var bell02 = new ChristmasBell("Bell 02");
3. Set ribbon color when creating the individual bells
// Define a custom constructor that sets 1 or more properties of a new object
var ChristmasBell = function (name, ribbonColor) {
    this.name = name;
    this.ribbonColor = ribbonColor || "red";
}

// Create individual bells
var bell01 = new ChristmasBell("Bell 01", "green");
var bell02 = new ChristmasBell("Bell 02");
What If...
ChristmasBell.prototype.ribbonColor = "yellow";