Created
June 10, 2013 04:20
-
-
Save mbbx6spp/5746516 to your computer and use it in GitHub Desktop.
Example of defining value constructors to build objects with information hiding abilities in Javascript.
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
var Car = function (make, model, year) { | |
var that = this; | |
var make = make; | |
var model = model; | |
var year = year; | |
that.getMake = function () { return make; }; | |
that.getModel = function () { return model; }; | |
that.getYear = function () { return year; }; | |
function valueOf(newPrice) { | |
var currentYear = (new Date()).getFullYear(); | |
var yearDiff = (currentYear - year); | |
var discountValue = yearDiff * newPrice * 0.15; | |
if ((newPrice - discountValue) > 0) { return (newPrice - discountValue); } | |
else { return 0; } | |
} | |
that.getCurrentValue = function (newPrice) { return valueOf(newPrice); }; | |
} | |
var neon = new Car("Ford", "Focus", 2002); | |
neon.getCurrentValue(16200); // should return with 0 | |
var elantra = new Car("Hyundai", "Elantra", 2011); | |
elantra.getCurrentValue(17965); // should return with 12575.50 | |
// Now let us try to get access to private make to modify it to cause mayhem: | |
elantra.make = "Ford"; // No error, but doesn't change the internal make value, which is good. | |
elantra.getMake(); // should return "Hyundai" as expected | |
// Almost exactly what we wanted. If only it threw some meaningful exception or error when assigning "Ford" to make on the object... | |
// Hope you enjoyed this really simple introduction. Cheers! Susan |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment