Skip to content

Instantly share code, notes, and snippets.

@varunkumar
Last active August 29, 2015 14:05
Show Gist options
  • Save varunkumar/29e2647183109674a258 to your computer and use it in GitHub Desktop.
Save varunkumar/29e2647183109674a258 to your computer and use it in GitHub Desktop.
OOP Template
"use strict"; // strict mode JS
// IIFE
(function () {
const Person = (function () {
// private static
var nextId = 1;
// constructor
var person = function () {
// private members
var _id, _firstName, _lastName, _age;
// public members (instance only)
// defining a read-only property named id with default-value set.
Object.defineProperty(this, 'id', {
value: nextId++,
writable: false,
enumerable: true
});
// defining a property named firstName using get and set methods.
Object.defineProperty(this, 'firstName', {
get: function() { return _firstName; },
set: function(value) {
if (typeof value === "string") {
_firstName = value;
} else
throw new TypeError("Invalid argument. String type was expected");
},
enumerable: true
});
Object.defineProperty(this, 'lastName', {
get: function() { return _lastName; },
set: function(value) {
if (typeof value === "string") {
_lastName = value;
} else
throw new TypeError("Invalid argument. String type was expected");
},
enumerable: true
});
Object.defineProperty(this, 'age', {
get: function() { return _age; },
set: function(value) {
if (!isNaN(value))
_age = value;
else
throw new TypeError("Invalid argument. Number type was expected");
},
enumerable: true
});
// locking this object to make sure no memers are added / removed. Members are still writeable.
Object.seal(this);
};
// public static. One can access with classname itslef
person.getNextId = function () {
return nextId;
};
var proto = {
// public (shared across instances)
clone : function() {
// note all the properties must be enumerable for $.extend to work. JSON.stringify also depends on 'enumerable'
// Set it explicitly to true.
return $.extend(true, new Person(), this);
}
};
// freezing the prototype so that one can't add / remove methods through prototype.
Object.freeze(proto);
person.prototype = proto;
return person;
})();
// freezing the class itself so that nobody changes the static members.
Object.freeze(Person);
var p1 = new Person();
p1.firstName = "Varunkumar";
p1.lastName = "Nagarajan";
p1.age = 29;
// this will result in error in strict mode but works fine in normal mode
//p1.email = "[email protected]";
//delete p1.firstName; // error
console.log(JSON.stringify(p1));
var p2 = p1.clone();
//p2.email = "[email protected]";
p2.firstName = "Arunkumar";
console.log("Next id: " + Person.getNextId());
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment