Skip to content

Instantly share code, notes, and snippets.

@saevarom
Forked from Integralist/Constructor.js
Last active October 7, 2015 14:13
Show Gist options
  • Save saevarom/68717139b6e4a995b594 to your computer and use it in GitHub Desktop.
Save saevarom/68717139b6e4a995b594 to your computer and use it in GitHub Desktop.
Private and Privileged methods using the Constructor pattern in JavaScript
var Booking = (function() {
var self = null;
// ------------------------------------------------------------
// constructor
function Booking(initial_data){
this.raw_data = initial_data;
this.json = null;
// needed for private methods
self = this;
parse_json();
}
// ------------------------------------------------------------
// public methods
Booking.prototype.get_json = function() {
return this.json;
}
Booking.prototype.get_confirmation_number = function() {
return this.json.confirmationNumber;
}
// ------------------------------------------------------------
// private methods
function parse_json(){
self.json = $.parseJSON(self.raw_data);
}
// ------------------------------------------------------------
// return constructor
return Booking;
})();
function Constructor(){
this.foo = 'foo';
// Needed for Private methods
var self = this;
// Private methods need to be placed inside the Constructor.
// Doesn't perform as well as prototype methods (as not shared across instances)
function private(){
console.log('I am private');
console.log(self.foo);
}
// Privileged methods need to be placed inside the Constructor.
// This is so they can get access to the Private methods.
this.privileged = function(){
private();
};
}
Constructor.prototype.public = function(){
console.log('I am public');
};
constructor = new Constructor;
console.log(constructor.foo);
constructor.public(); // will work
constructor.privileged(); // will work
constructor.private(); // won't work (can't be accessed directly)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment