Skip to content

Instantly share code, notes, and snippets.

@shamsher31
Created August 27, 2015 06:13
Show Gist options
  • Save shamsher31/137274bba22514b66dfd to your computer and use it in GitHub Desktop.
Save shamsher31/137274bba22514b66dfd to your computer and use it in GitHub Desktop.
Javascript Closure
// returns an object that does not itself possess "var a"
// The closure gives indirect access to a, via the public getter and setter.
function f() {
var a = 1;
return {
getA: function() {
return a;
},
setA: function( A ) {
a = A;
}
};
}
var MyObj = new f();
alert(MyObj.a); // --> undefined
alert(MyObj.getA()); // --> 1
MyObj.setA(5);
alert(MyObj.getA()); // --> 5
function showName() {
var name = 'Sam';
console.log(name);
}
showName();
function celebrityID() {
var celebID = 8978789;
return {
getID : function() {
return celebID;
},
setID : function(newID) {
celebID = newID;
}
}
}
function empID() {
var eId = 9999;
return {
getID : function() {
return eId;
},
setID : function(newID) {
eID = newID;
}
}
}
var emp = empID();
console.log(emp.getID);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment