Created
May 16, 2010 16:04
-
-
Save funkatron/402961 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
constructor for Robot | |
*/ | |
var Robot = function(name) { | |
this.name = name; | |
}; | |
/* | |
property in prototye | |
*/ | |
Robot.prototype.name = null; | |
/* | |
redefine toString | |
*/ | |
Robot.prototype.toString = function() { | |
return '[Robot named '+this.name+']'; | |
}; | |
Robot.prototype.shutDown = function() { | |
console.log(this.name + ' is shutting down…'); | |
}; | |
Robot.prototype.say = function(something) { | |
console.log("In a robot voice, "+this.name+" says:\n"+something); | |
}; | |
/* | |
constructor for new object | |
*/ | |
var Robocop = function(name) { | |
this.name = name; | |
}; | |
/* | |
inherit the prototype of Robot | |
*/ | |
Robocop.prototype = new Robot(); | |
/* | |
redefine toString | |
*/ | |
Robocop.prototype.toString = function() { | |
return '[Robocop named '+this.name+']'; | |
}; | |
/* | |
add a new method | |
*/ | |
Robocop.prototype.arrest = function() { | |
this.say('Come with me or there will be… trouble'); | |
}; | |
/* | |
this redefines shutDown and calls the "parent" version as well | |
*/ | |
Robocop.prototype.shutDown = function() { | |
this.say(this.name+' requires sleep!'); | |
Robot.prototype.shutDown.call(this); | |
}; | |
/* | |
Make a couple functions to check instanceof | |
*/ | |
function is_robot(obj) { | |
if (obj instanceof Robot) { | |
console.log(obj.name + ' is a Robot'); | |
} else { | |
console.log(obj.name + ' is NOT a Robot'); | |
} | |
} | |
function is_robocop(obj) { | |
if (obj instanceof Robocop) { | |
console.log(obj.name + ' is a Robocop'); | |
} else { | |
console.log(obj.name + ' is NOT a Robocop'); | |
} | |
} | |
/* | |
now make a couple object instances | |
*/ | |
var robby = new Robot('Robby'); | |
console.log(robby.toString()); | |
robby.shutDown(); | |
is_robot(robby); | |
is_robocop(robby); | |
var murphy = new Robocop('Murphy'); | |
console.log(murphy.toString()); | |
murphy.arrest(); | |
is_robot(murphy); | |
is_robocop(murphy); | |
/* | |
add a new function to the base prototype | |
*/ | |
Robot.prototype.shockAttack = function() { | |
console.log(this.name + " zaps you!"); | |
} | |
/* | |
use the new function in an inheriting object | |
*/ | |
murphy.shockAttack(); | |
murphy.shutDown(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment