Javascript Interview. Prototype Inheritance
HTML
<script>
function assert(pass, msg) {
var type = pass ? "PASS" : "FAIL";
jQuery("#results").append("<li class='" + type + "'><b>" + type + "</b> " + msg + "</li>");
}
function error(msg) {
jQuery("#results").append("<li class='ERROR'><b>ERROR</b> " + msg + "</li>");
}
function log() {
var msg = "";
for (var i = 0; i < arguments.length; i++) {
msg += " " + arguments[i];
}
jQuery("#results").append("<li class='LOG'><b>LOG</b> " + msg + "</li>");
}
</script>
<div id="results"></div>
JavaScript
// Create and define Adult.
function Adult() {}
Adult.prototype.speak = function(){
return 'I am an adult!';
};
Adult.prototype.workDay= function(){
return 'I have to go to work.';
};
// Create and define Student.
function Student() {
}
//1. Tell Student to inherit Adult.
//TODO: implement here
//2. Change the workDay method of Student so it returns "I have to do my homework."
//TODO: implement here
try {
var adult = new Adult();
assert(adult.workDay() === 'I have to go to work.', "Ensure method called from Adult");
assert(adult.speak() === "I am an adult!", "Ensure speak method works as well");
var student = new Student();
assert(student.workDay() === "I have to do my homework.", "Ensure method called from Student");
assert(student.speak() === "I am an adult!", "Ensure parent method works as well");
//3. TODO: To check for inheritance replace ___ with true/false:
assert(student instanceof Adult === ___ , "Should be instance of Adult?");
assert(student instanceof Student === ___, "Should be instance Student?");
} catch(e) {
assert(false, "Unexpected error occured");
}