xxxxxxxxxx
//more examples isgoodstuff.com/2011/10/16/wth-is-encapsulating-javascript/
var calc = function(){
return {};
}
//Secondary Namespace calc.sum - wrapped using self triggering function
calc.sum = function(){
/* private variables only to calc.sum see how variables are kept within */
var value1 = 0;
var value2 = 0;
// private method to calc.sum
function calc(){
var sum = parseInt(value1) + parseInt(value2);
return sum;
}
// public functions
return {
init: function(external_value1, external_value2){
this.setValue1(external_value1);
this.setValue2(external_value2);
},
setValue1: function(val){
value1 = val;
},
setValue2: function(val){
value2 = val;
},
getSum: function(){
// calling an internal private function
// (requires no "this.")
return calc();
}
}
}();
xxxxxxxxxx
//encapsulation example
class person{
constructor(name,id){
this.name = name;
this.id = id;
}
add_Address(add){
this.add = add;
}
getDetails(){
console.log(`Name is ${this.name},Address is: ${this.add}`);
}
}
let person1 = new person('Mukul',21);
person1.add_Address('Delhi');
person1.getDetails();