Skip to content

Instantly share code, notes, and snippets.

@Nabid
Last active December 30, 2015 19:03
Show Gist options
  • Save Nabid/b121f13ef071d64d8cda to your computer and use it in GitHub Desktop.
Save Nabid/b121f13ef071d64d8cda to your computer and use it in GitHub Desktop.
Encapsulation example in JS
/*
This is a demonstration of JavaScript ENCAPSULATION.
Declaring private and public properties in JavaScript
is quite simple, but it is difficult to understand
how to access and update them.
If you are not familiarized with namespaces, just remove
appearances of "Prome.Test" and tweak the errors!!!
*/
var Prome = Prome || {};
Prome.Test = Prome.Test || {};
// AppController constructors
Prome.Test.AppController = function(param){
// public properties
this.PI = 2 * Math.acos(0.0);
this.param = param;
// private properties
var value = "This is a private value";
// private method
// this will access/return private variable "value"
function getValue() {
return value;
}
// privileged public method to access private methods
// this will access/call private method "getValue()"
this.accessPrivate = function() {
return getValue();
};
// closure
// closures are wonderful mechanism to declare
// and access private properties. these properties
// can also be initialized through self-invoking
// function call.
this.closure = (function(value){
var privateValue = value;
console.log("[privateValue]",privateValue);
return {
add : function(value){
privateValue += value;
},
get : function(){
return privateValue;
}
};
})(0);
};
Prome.Test.AppController.prototype.main = function(){
console.group("JS Encapsulation");
// accessing public properties
console.log("[this.param]", this.param);
console.log("[this.PI]", this.PI);
// accessing private proterty through private method
// through public method!!!
// call = accessPrivate -> getValue -> value
console.log("[this.accessPrivate()]", this.accessPrivate());
// accessing private properties and methods
// these will cause ERROR!!!
try {
console.log("[value]", value);
} catch(ex) {
console.log("[ERROR]", ex);
};
try {
console.log("[getValue()]", getValue());
} catch(ex) {
console.log("[ERROR]", ex);
};
// accessing closure :)
this.closure.add(5);
console.log("[this.closure.get()]", this.closure.get());
this.closure.add(4);
console.log("[this.closure.get()]", this.closure.get());
console.groupEnd();
};
// self-invoking function or IIFE
(function(){
var app = new Prome.Test.AppController("this is public!!!");
app.main();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment