Skip to content

Instantly share code, notes, and snippets.

@dprea
Last active February 12, 2016 04:44
Show Gist options
  • Save dprea/f5458bbcdae4318e6c8a to your computer and use it in GitHub Desktop.
Save dprea/f5458bbcdae4318e6c8a to your computer and use it in GitHub Desktop.
IIFE - Encapsulation Reference
/**
* IIFE vs NFE
* -----------------------------------
* The Demo Below can easily be switched between
* a Self Invoking Function Expression and a
* Named Function Expression.
*
* Immediately Invoking Function Expression
* -----------------------------------
* (function() {}());
*
* Named Function Expression
* -----------------------------------
* var app = (function() {}());
* Add init function to app service.
* Usage: app.init(); || app.method();
* -----------------------------------
* @author: Dustin Rea
* -----------------------------------
* TODO: Experiment with using this
* -----------------------------------
*/
(function() {
'use strict';
var error = null;
var name = 'Jankular';
var user = {name: ''};
// The Exposed Object Service
var app = {
logName: logName,
setUserName: setUserName,
logUserName: logUserName,
getUser: getUser // Only Exposed for Testing
};
// --- PUBLIC ENCAPSULATED SERVICE ---
// Return a Service to use Outside
//return app; // Add init: init to app to Init outside.
// Return app after init
//return app;
// --- PRIVATE ENCAPSULATION ---
// Run Init with full encapsulation
init();
function init() {
console.log('--- App Name ---');
logName();
console.log('--- User Object --- ');
console.log(getUser());
console.log('--- Setting Username: Type Error ---');
setUserName(9999);
logUserName();
console.log('--- Updated User Object --- ');
console.log(getUser());
console.log('--- Setting Username: Success ---');
setUserName('John Smith');
logUserName();
console.log('--- Updated User Object --- ');
console.log(getUser());
return app;
}
/////////////////////////////
// Private Functions
function log(input) {
console.log(input);
}
function logError() {
log(error);
error = null;
return;
}
function getName() {
return name;
}
function getUser() {
return user;
}
function getUserName() {
return user.name;
}
// Public Functions
function logName() {
return log(getName());
}
function logUserName() {
return log(getUserName());
}
// Sets the Username | Type Check for String
function setUserName(name) {
if(typeof name !== 'string') {
error = 'Please Use Letters Only.';
logError();
} else {
user.name = name;
}
}
}());
// For Named Function Expression
// var app = (function() {}());
// Add init function to app service.
//app.init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment