I want to implement data hiding in JavaScript by writing a function that returns an object from inside a closure. Here is the incorrect code:
pokerObjects.getPokerCard = (function(f, s){
// These are immutable, so hide them in the closure
var face = (typeof f === 'number' ? pokerObjects.faces[f] : f);
var suit = (typeof s === 'number' ? pokerObjects.suits[s] : s);
return {
to_s: function() { return face + " of " + suit; }
};
})(f,s);
What I would like to do is be able to call the function getPokerCard with two parameters and have those parameters passed to the anonymous function defined parenthetically. But, passing them as written above gives me a ReferenceError: f is not defined when I try to parse the code.
Maybe I’m not understanding your question correctly, but it seems like you want to assign a function to pokerObjects.getPokerCard which would allow you to later call pokerObjects.getPokerCard(f, s) which returns the object with getFace, getSuit, and to_s.
This accomplishes the same thing, while still ensuring that face and suit remain hidden. They are scoped variables within the function.