简体   繁体   中英

Private variable not staying private in JS module

After reading the following article, http://javascriptplayground.com/blog/2012/04/javascript-module-pattern/ I have decided to start implementing modules in my JS.

Unfortunately, the module I am using does not seem to be keeping the private variable private,

var popoverOptionsModule = (function() {
var _stopAskingList = [];

var addToStopAskingList = function(itemToAdd) {
    if (_stopAskingList.indexOf(itemToAdd) === -1){
      _stopAskingList.push(itemToAdd);
    }
}

var getStopAskingList = function() {
    return _stopAskingList;
}


return {
    addToStopAskingList: addToStopAskingList,
    getStopAskingList: getStopAskingList,
};
})();

popoverOptionsModule._stopAskingList = 4;
console.log(popoverOptionsModule._stopAskingList);

As you can see, I am able to change the value of popoverOptionsModule._stopAskingList and log the update to the console... I thought this was not supposed to happen. Thanks for your help!

JS is completely dynamically typed, so when you have the line

popoverOptionsModule._stopAskingList = 4;

You've just created this variable and assigned it a value, hence why the next line succeeds. If you didn't have this line, then the subsequent console.log would report undefined. This code would work too

popoverOptionsModule._abc = 4;
console.log(popoverOptionsModule._abc);

Remember that this isn't actually a private variable in the same way that OO languages implement protection levels, rather it's just an API pattern that attempts to hide it from the caller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM