-
-
Save saevarom/68717139b6e4a995b594 to your computer and use it in GitHub Desktop.
Private and Privileged methods using the Constructor pattern in JavaScript
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 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; | |
})(); | |
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
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