Skip to content

Instantly share code, notes, and snippets.

@andy-polhill
Created June 10, 2015 11:03
Show Gist options
  • Save andy-polhill/e063a1bcf690a36f560d to your computer and use it in GitHub Desktop.
Save andy-polhill/e063a1bcf690a36f560d to your computer and use it in GitHub Desktop.
ES6 Person class
var Person = (function(){
var population = 0;
var privateData = new WeakMap();
class Person {
constructor(opts) {
privateData.set(this, {
dob: opts.dob,
});
this.name = opts.name,
Object.seal(this);
Person.incrementPopulation();
}
//Public
greet() {
console.log('Hello my name is ' + this.name +
' and I am ' + this.age + ' years old');
};
get age() {
return new Date().getFullYear() - privateData.get(this).dob.getFullYear();
};
static getPopulation() {
return population;
};
static incrementPopulation() {
population++;
};
};
return Person;
})();
var andy = new Person({
name: 'Andy',
dob: new Date('12/13/1979')
});
Person.population = 200;
console.log(Person.getPopulation());
var dave = new Person({
name: 'Dave',
dob: new Date('03/09/1984')
});
console.log(Person.getPopulation());
//andy.dob = new Date('12/13/1990');
//andy.age = 22;
andy.greet();
andy.name = "Andrew";
console.log(andy.name);// = 'Andrew';
//andy.set('name', 'Andrew');
andy.greet();
dave.greet();
@andy-polhill
Copy link
Author

It would be nice to do away with the closure around the class, but at the moment that encapsulates the private population variable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment