Getter/setter on javascript array?

前端 未结 10 2174
闹比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:47

    Using Proxies, you can get the desired behavior:

    var _arr = ['one', 'two', 'three'];
    
    var accessCount = 0;
    function doSomething() {
      accessCount++;
    }
    
    var arr = new Proxy(_arr, {
      get: function(target, name) {
        doSomething();
        return target[name];
      }
    });
    
    function print(value) {
      document.querySelector('pre').textContent += value + '\n';
    }
    
    print(accessCount);      // 0
    print(arr[0]);           // 'one'
    print(arr[1]);           // 'two'
    print(accessCount);      // 2
    print(arr.length);       // 3
    print(accessCount);      // 3
    print(arr.constructor);  // 'function Array() { [native code] }'

    The Proxy constructor will create an object wrapping our Array and use functions called traps to override basic behaviors. The get function will be called for any property lookup, and doSomething() before returning the value.

    Proxies are an ES6 feature and are not supported in IE11 or lower. See browser compatibility list.

提交回复
热议问题