0

Using the revealing module pattern, how can I provide direct access to non-static private variables? Here's what I have:

var M = function () {
    var obj = {};
    var arr = [];
    var change = function () {
        obj = {"key":"if I see this, O is a reference to obj"};
        arr.push("If I see this, A is a reference to arr")
        };
    return {
        change: change,
        O: obj,
        A: arr
        };
}();

M.change();
console.log(M.A); // prints ["If I see this, A is a reference to arr"] 
console.log(M.O); // prints Object {}, wanted "if I see this, O..."

It seems that A references arr directly, while O settles for a copy of obj's value at initialization time. I would understand the behavior if obj were a string, float, or boolean.

I could of course expose obj via a public get_obj method, but I'm still curious if this can be solved without additional help methods (I want to keep the interface to obj intact). Furthermore, what's so special about arrays that objects don't have, that causes this behavior?

Really grateful for any insights,

o-o
  • 8,158
  • 2
  • 20
  • 21
  • In `change`, you're re-setting value of the `obj` variable, but modifying the `arr` variable in place. `M.A` and `M.O` are references to the values that `arr` and `obj` held at that point. Changing the value of the `obj` and `arr` variables doesn't affect `M`. There's no copying done. Maybe you meant to do `obj.key = "if I see this...";`. If you want to reset the whole `obj` and only have one key/value pair in it, you can loop through it and `delete` properties, then use `.key = "if I see this..."` – Ian Jul 25 '13 at 17:21
  • Ah, I see, and changing O.key did the trick. In my original code I had 'O = d3.layout.force()' which is quite a complex object... =/ – o-o Jul 25 '13 at 18:53

1 Answers1

1
obj["key"] = "if I see this, O is a reference to obj";

You can set the key property for obj and keep the reference to the original object.

vsr
  • 3,138
  • 1
  • 19
  • 14