0

这就是我遇到的……我设计我的对象:

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 

这显然会更改引用,但不会更改对象内部的引用。创建 Getter/Setter 函数是避免这种情况发生的唯一方法吗?

4

1 回答 1

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

Will work from the outside, since this will refer to the instance. 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; }; 
于 2012-09-21T19:09:27.670 回答