Skip to content

Instantly share code, notes, and snippets.

@jzfgo
Forked from funkatron/Prototype_Inheritance.js
Created May 16, 2010 16:24
Show Gist options
  • Save jzfgo/402973 to your computer and use it in GitHub Desktop.
Save jzfgo/402973 to your computer and use it in GitHub Desktop.
/*
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