Created
June 10, 2015 11:03
-
-
Save andy-polhill/e063a1bcf690a36f560d to your computer and use it in GitHub Desktop.
ES6 Person class
This file contains hidden or 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 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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It would be nice to do away with the closure around the class, but at the moment that encapsulates the private population variable.