a/20287172/1636522
CSS
*{font-family:Consolas}
JavaScript
// Buddy
var Buddy = function (name) {
this.name = name;
};
Buddy.prototype.speak = function (something) {
output(this.name + ' : ' + something);
};
// SuperBuddy
var SuperBuddy = function () {
Buddy.apply(this, arguments);
this.shout = function (something) {
this.speak(something.toUpperCase());
};
};
SuperBuddy.prototype = Object.create(Buddy.prototype);
SuperBuddy.prototype.introduce = function () {
this.speak('Hi, I\'m ' + this.name + '.');
};
// buddies
var foo = new Buddy();
var bar = new SuperBuddy('Bar');
var baz = new SuperBuddy('Baz');
// discussion
try {
foo.speak('I\'m so shy...');
foo.introduce();
} catch(e) {
output(e);
}
foo.speak('Am I a Buddy?');
baz.speak(is(foo, Buddy));
foo.speak('Am I a SuperBuddy?');
baz.speak(is(foo, SuperBuddy));
foo.speak('Too bad...');
output('-');
bar.introduce();
bar.speak('Am I a Buddy?');
baz.speak(is(bar, Buddy));
bar.speak('Am I a SuperBuddy?');
baz.speak(is(bar, SuperBuddy));
bar.shout('This is cool!');
output('-');
output('Let\'s change "speak" and "shoot" methods.');
Buddy.prototype.speak = function (something) {
output(this.name + ' : <b>' + something + '</b>');
};
baz.shout = function (something) {
this.speak('<span style="color:blue">' + something.toUpperCase() + '</span>');
};
foo.speak('I speak in BOLD...');
bar.speak('Same for me! Lol!');
baz.shout('I can shout in blue!');
bar.shout('This is unfair!');
// helpers
function is(inst, Class) {
return inst instanceof Class ? 'Yes.' : 'No.';
}
function output(s) {
document.body.innerHTML += (
s instanceof Error ? '<div style="color:red">' : '<div>'
) + s + '</div>';
}