简体   繁体   English

Javascript揭示模块模式-参考

[英]Javascript revealing module pattern - references

Here's what I've run into... I design my object: 这是我遇到的问题...我设计了对象:

var Tab = function () {
    var _data = [], _owners = [], _supportWorkers = [], _watchers = [];
        var _dataLength = function () { return _data.length; };
    return {
        Data: _data,
        Owners: _owners,
        SupportWorkers: _supportWorkers,
        Watchers: _watchers,
            Length: _dataLength
    };
};

var newObject = new Tab();
newObject.Data = [{"my":"data"}];
alert(newObject.Length()); // Length == 0
alert(newObject.Data.length);​ // Length == 1 

This obviously changes the reference, but does not change the reference INSIDE the object. 这显然会更改引用,但不会更改对象内部的引用。 Is creating a Getter/Setter function the only way to avoid this from happening? 创建Getter / Setter函数是避免这种情况发生的唯一方法吗?

var _dataLength = function () { return this.Data.length; };

Will work from the outside, since this will refer to the instance. 从外部开始工作,因为this将引用实例。 It will not work from within the module itself. 它不能在模块本身内部工作。


Here's how I would do it - the revealing module pattern is pointless if all your data is revealed: 这是我的操作方式-如果您的所有数据都被显示,则显示模块模式毫无意义:

var Tab = function () { 
    this.data = [];
    this.owners = [];
    this.supportWorkers = [];
    this.watchers = [];
}
Tab.prototype.dataLength = function () { return this.data.length; }; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM