JS: revealing module pattern - accessing internal objects vs arrays?

自闭症网瘾萝莉.ら 提交于 2020-01-25 12:24:05

问题


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:


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.



来源:https://stackoverflow.com/questions/17864608/js-revealing-module-pattern-accessing-internal-objects-vs-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!