JS: revealing module pattern - accessing internal

2019-09-15 03:51发布

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,

1条回答
2楼-- · 2019-09-15 04:20
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.

查看更多
登录 后发表回答