Skip to content

Instantly share code, notes, and snippets.

@andy-polhill
Last active August 29, 2015 14:22
Show Gist options
  • Save andy-polhill/58f0a3c101b9d1011216 to your computer and use it in GitHub Desktop.
Save andy-polhill/58f0a3c101b9d1011216 to your computer and use it in GitHub Desktop.
ES5 Person Class
var Person = (function() {
var __population = 0;
function Person(opts) {
var privateProps = ['dob'];
//Private
var props = {
name: opts.name,
dob: opts.dob,
get age() {
return new Date().getFullYear() - this.dob.getFullYear();
}
};
//Priviledged
this.get = function (prop) {
return props[prop];
};
this.set = function (prop, value) {
if(privateProps.indexOf(prop) < 0) {
props[prop] = value;
}
};
Object.seal(this);
Person.incrementPopulation();
}
Person.prototype = {
//Public
greet: function() {
console.log('Hello my name is ' + this.get('name') +
' and I am ' + this.get('age') + ' years old');
}
};
Person.getPopulation = function() {
return __population;
};
Person.incrementPopulation = function() {
__population++;
};
Object.freeze(Person);
return Person;
})();
var andy = new Person({
name: 'Andy',
dob: new Date('12/13/1979')
});
console.log(Person.getPopulation());
var dave = new Person({
name: 'Dave',
dob: new Date('03/09/1984')
});
Person.population = 100;
console.log(Person.population);
console.log(Person.getPopulation());
andy.set('dob', new Date('12/13/1990'));
andy.greet();
andy.set('name', 'Andrew');
andy.greet();
dave.greet();
@andy-polhill
Copy link
Author

Arguable all of the static method stuff is a bit wrong, a Factory would probably be a better way to handle the population control.

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