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,

2
  • 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..." Commented Jul 25, 2013 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... =/ Commented Jul 25, 2013 at 18:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.