Skip to content

Instantly share code, notes, and snippets.

@mbbx6spp
Created June 10, 2013 04:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbbx6spp/5746516 to your computer and use it in GitHub Desktop.
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.
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