Getter/setter on javascript array?

前端 未结 10 2200
闹比i
闹比i 2020-12-01 02:12

Is there a way to get a get/set behaviour on an array? I imagine something like this:

var arr = [\'one\', \'two\', \'three\'];
var _arr = new Array();

for (         


        
10条回答
  •  被撕碎了的回忆
    2020-12-01 02:49

    this is the way I do things. You will have to tweak the Prototype Creation (I removed a bit from my Version). But this will give you the default getter / setter behavior I am used to in other Class-Based Languages. Defining a Getter and no Setter means that writing to the element will be ignored...

    Hope this helps.

    function Game () {
      var that = this;
      this._levels = [[1,2,3],[2,3,4],[4,5,6]];
    
      var self = {
        levels: [],
        get levels () {
            return that._levels;
        },
        setLevels: function(what) {
            that._levels = what;
            // do stuff here with
            // that._levels
        }
      };
      Object.freeze(self.levels);
      return self;
    }
    

    This gives me the expected behavior of:

    var g = new Game()
    g.levels
    /// --> [[1,2,3],[2,3,4],[4,5,6]]
    g.levels[0]
    /// --> [1,2,3]
    

    Taking up the critizism from dmvaldman: Writing should now be impossible. I rewrote the code to 1)not use depracated elements (__ defineGetter __) and 2) not accept any writing (that is: uncontrolled writing) to the levels element. An example setter is included. (I had to add spacing to __ defineGetter because of markdown)

    From dmvaldmans request:

    g.levels[0] = [2,3,4];
    g.levels;
    /// --> [[1,2,3],[2,3,4],[4,5,6]]
    
    //using setter
    g.setLevels([g.levels, g.levels, 1,2,3,[9]]);
    g.levels;
    /// --> [[[1,2,3],[2,3,4],[4,5,6]],[[1,2,3],[2,3,4],[4,5,6]], ....]
    
    //using setLevels
    g.setLevels([2,3,4]);
    g.levels;
    /// --> [2,3,4]
    

提交回复
热议问题