Created
April 30, 2014 19:30
-
-
Save reergymerej/aa6677926749c436f8ac to your computer and use it in GitHub Desktop.
This example shows that private variables created with module pattern may not be as private as you think.
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
var foo = (function () { | |
// create a private variable | |
var priv = []; | |
// expose getter/setter | |
return { | |
getPriv: function () { | |
return priv; | |
}, | |
setPriv: function (x) { | |
priv = x; | |
} | |
} | |
}()); | |
// Can we set it? | |
foo.setPriv([1, 2, 3]); | |
// Can we get it? | |
console.log(foo.getPriv()); // [1, 2, 3] | |
// Is priv private? | |
console.log(foo.priv); // undefined | |
// Is it *really* private? | |
foo.getPriv().splice(1, 1); | |
console.log(foo.getPriv()); // [1, 3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment