Last active
August 29, 2015 13:56
-
-
Save mucaho/8877370 to your computer and use it in GitHub Desktop.
JavaScript prototype template
This file contains 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() { | |
// private statics | |
var greetHeader = "Welcome,"; | |
var greetFooter = "! Have a nice day!"; | |
// constructor -- define instance specific stuff | |
function Person(isMale, firstName, lastName) { | |
this.firstName = firstName; | |
this.lastName = lastName; | |
// modifiable public field | |
this.userData = null; | |
// instance private fields | |
Object.defineProperty(this, "_gender", { | |
enumerable: false, | |
configurable: false, | |
writable: false, | |
value: (isMale ? "Mr" : "Ms") | |
}); | |
// prevent extension of instance | |
Object.seal(this); | |
} | |
// public final class statics (accessed via Person.serialVersionUID) | |
Person.serialVersionUID = "AA2q9AalA729L"; | |
// freeze class | |
Object.freeze(Person); | |
// instance public methods | |
Person.prototype.constructor = Person; | |
Person.prototype.toString = function() { | |
return greetHeader + " " + this._gender + " " + this.firstName + " " + | |
this.lastName + " " + greetFooter; | |
} | |
// instance public fields (getters & setters) | |
var fields = ['firstName','lastName']; | |
fields.forEach(function(fieldName) { | |
Object.defineProperty (Person.prototype, fieldName, { | |
configurable: false, | |
enumarable: true, | |
get: function () { return this["_"+fieldName]; }, | |
set: function (value) { this["_"+fieldName] = value; } | |
}); | |
}); | |
// public final instance statics (accessed via personInstance.serialVersionUID) | |
Person.prototype.serialVersionUID = "AA2q9AalA729L"; | |
// freeze prototype | |
Object.freeze(Person.prototype); | |
return Person; | |
})(); | |
var max = new Person(true, "Max", "Payne"); | |
var sarah = new Person(false, "Sarah", "Connor"); | |
console.log(max.toString()); | |
console.log(max); | |
console.log(sarah.toString()); | |
console.log(sarah); | |
console.log(); | |
console.log(Person.serialVersionUID); | |
console.log(max.serialVersionUID); | |
console.log(); | |
sarah.lastName = max.lastName; | |
console.log(max.toString()); | |
console.log(sarah.toString()); | |
console.log(); | |
max.toString = function() { return ""}; | |
console.log(max.toString()); | |
max.gender = "Ms"; | |
console.log(max.toString()); | |
console.log(); | |
sarah.foo = "bar"; | |
console.log(sarah.foo); | |
Person.foo = "bar"; | |
console.log(Person.foo); | |
console.log(); | |
console.log(sarah.userData); | |
sarah.userData = "I fight Skynet!"; | |
console.log(sarah.userData); | |
console.log(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment