Last active
August 29, 2015 14:22
-
-
Save andy-polhill/58f0a3c101b9d1011216 to your computer and use it in GitHub Desktop.
ES5 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; | |
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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Arguable all of the static method stuff is a bit wrong, a Factory would probably be a better way to handle the population control.