So, we know the module pattern provides privacy in JS by creating closures and providing getters/setters to manage access to the variables. That's cool, but you have to remember that everything in JavaScript is passed by reference.
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] |
Since we're returning the actual array, the caller can have its way with it through splice. Dang, looks like we have to return a copy of the value instead.
No comments:
Post a Comment