Skip to content

Instantly share code, notes, and snippets.

@reergymerej
Created April 30, 2014 19:30
Show Gist options
  • Save reergymerej/aa6677926749c436f8ac to your computer and use it in GitHub Desktop.
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.
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