Last active
August 29, 2015 14:07
-
-
Save stevobengtson/c2054a6efd44f6cb775f to your computer and use it in GitHub Desktop.
Javascript Objects
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
/** | |
* Public Javascript Object | |
*/ | |
function Shape(sides, fillColor, strokeColor) { | |
// Public properties | |
this.sides = sides; | |
this.fillColor = fillColor; | |
this.strokeColor = strokeColor; | |
// Private properties | |
var angle = 0; | |
// Private methods | |
function doRotate(newAngle) { | |
angle = newAngle; | |
} | |
// Privileged methods | |
this.rotate = function(degrees) { | |
var newAngle = angle + degrees; | |
doRotate(newAngle); | |
}; | |
this.getAngle = function() { | |
return angle; | |
}; | |
} | |
// Public method | |
Shape.prototype.drawShape = function() { | |
console.log('I am a shape with ' + this.sides + ' sides.'); | |
console.log(' I have an angle of ' + this.getAngle() + ' degrees.'); | |
}; | |
// Test | |
var myShape = new Shape(3, 'red', 'black'); | |
myShape.rotate(45); | |
myShape.drawShape(); // Ouputs 3 sides and 45 degrees | |
console.log('Test access private property: ' + myShape.angle); // Undefined | |
console.log('Test access priviledged method: ' + myShape.getAngle()); // 45 | |
myShape.sides = 5; | |
myShape.drawShape(); // Outputs 5 sides and 45 degrees |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment