JS:显示模块模式-访问内部对象还是数组? [英] JS: revealing module pattern - accessing internal objects vs arrays?

查看:185
本文介绍了JS:显示模块模式-访问内部对象还是数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用显示模块模式,如何为非静态私有变量提供直接访问?这就是我所拥有的:

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..."

似乎A直接引用了arr,而O在初始化时决定了obj值的副本.如果obj是字符串,float或boolean,我会理解这种行为.

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.

我当然可以通过公共的get_obj方法公开obj,但是我仍然很好奇是否可以在没有其他帮助方法的情况下解决这个问题(我想保持obj的 interface 完好无损).此外,对象没有的数组有什么特别之处,会导致这种现象?

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,

推荐答案

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

您可以为obj设置key属性,并保留对原始对象的引用.

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

这篇关于JS:显示模块模式-访问内部对象还是数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆