// 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");
Implement lightUp method for all bells,
ie. bell01.lightUp() outputs to console
Fix easy misuse of current constructor,
ie. var cowBell = new bell("Cow Bell").
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");