Skip to content

Instantly share code, notes, and snippets.

@jaywon
Created August 9, 2014 12:15
Show Gist options
  • Save jaywon/54338d420801e3e4e5fb to your computer and use it in GitHub Desktop.
Save jaywon/54338d420801e3e4e5fb to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
</body>
</html>
function Box(){
//constructor goes here
this.name = "Box";
}
Box.prototype.draw = function() {
console.log(this.name + " drawing!");
};
console.log("Box prototype", Box.prototype);
console.log("Box constructor", Box.prototype.constructor);
function Square(){
Box.call(this); //call base constructor to set up it's this.name
//class specific constructors to this class
this.name = "Square";
}
console.log("Square Prototype before:", Square.prototype);
//set the Square prototype to the Box prototype to get its draw method
Square.prototype = Object.create(Box.prototype);
console.log("Square Prototype after:", Square.prototype);
console.log("Square Constructor before:", Square.prototype.constructor);
//Since functions can be used as values give the constructor property the Square() function defined above to call the Square() function when it is created instead of Box().
Square.prototype.constructor = Square;
console.log("Square Constructor after:", Square.prototype.constructor);
function Rectangle(){
Box.call(this); //call base constructor to set up it's name
//class specific constructors to this class
this.name = "Rectangle";
}
console.log("Rectangle Prototype before:", Rectangle.prototype);
//set the Rectangle prototype to the Box prototype to get its draw method
Rectangle.prototype = Object.create(Box.prototype);
console.log("Rectangle Prototype after:", Rectangle.prototype);
console.log("Rectangle Constructor before:", Rectangle.prototype.constructor);
//Since functions can be used as values give the constructor the Rectangle() function defined above to call the Rectangle() function when it is created instead of Box()
Rectangle.prototype.constructor = Rectangle;
console.log("Rectangle Constructor after:", Rectangle.prototype.constructor);
//create new objects and call their draw() function that was only added to the Box class
var mySquare = new Square();
var myRectangle = new Rectangle();
console.log("Square is typeof Box: ", (mySquare instanceof Box));
console.log("AND Square is typeof Square:", (mySquare instanceof Square));
console.log("Rectangle is typeof Box:", (myRectangle instanceof Box));
console.log("AND Rectangle is typeof Rectangle:", (myRectangle instanceof Rectangle));
mySquare.draw();
myRectangle.draw();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment