Skip to content

Instantly share code, notes, and snippets.

@ernestlv
Created November 7, 2016 17:59
Show Gist options
  • Save ernestlv/a79994df8a29faad29bc3a7a4974c503 to your computer and use it in GitHub Desktop.
Save ernestlv/a79994df8a29faad29bc3a7a4974c503 to your computer and use it in GitHub Desktop.
create private properties in ES6 class using weakmaps
// taken from https://www.sitepoint.com/object-oriented-javascript-deep-dive-es6-classes/
let SimpleDate = (function() {
let _years = new WeakMap();
let _months = new WeakMap();
let _days = new WeakMap();
class SimpleDate {
constructor(year, month, day) {
// Check that (year, month, day) is a valid date
// ...
// If it is, use it to initialize "this" date
_years.set(this, year);
_months.set(this, month);
_days.set(this, day);
}
addDays(nDays) {
// Increase "this" date by n days
// ...
}
getDay() {
return _days.get(this);
}
}
return SimpleDate;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment