Created
August 27, 2015 06:13
-
-
Save shamsher31/137274bba22514b66dfd to your computer and use it in GitHub Desktop.
Javascript Closure
This file contains 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
// 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