Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getter/setter on javascript array?

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 (var i = 0; i < arr.length; i++) {     arr[i].__defineGetter__('value',         function (index) {             //Do something             return _arr[index];         });     arr[i].__defineSetter__('value',         function (index, val) {             //Do something             _arr[index] = val;         }); } 
like image 996
Martin Hansen Avatar asked Mar 15 '10 17:03

Martin Hansen


People also ask

Are there getters and setters in JavaScript?

JavaScript Accessors (Getters and Setters)ECMAScript 5 (ES5 2009) introduced Getter and Setters. Getters and setters allow you to define Object Accessors (Computed Properties).

What is get () in JavaScript?

The get syntax binds an object property to a function that will be called when that property is looked up.

What is the difference between getter and setter in JavaScript?

Getters and setters allow us to define Object Accessors. The difference between them is that the former is used to get the property from the object whereas the latter is used to set a property in an object.

How do setters work in JavaScript?

In JavaScript, a setter can be used to execute a function whenever a specified property is attempted to be changed. Setters are most often used in conjunction with getters to create a type of pseudo-property. It is not possible to simultaneously have a setter on a property that holds an actual value.


1 Answers

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] }'
<pre></pre>

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.

like image 57
aebabis Avatar answered Sep 20 '22 02:09

aebabis