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 (
I looked up in John Resig's article JavaScript Getters And Setters, but his prototype example didn't work for me. After trying out some alternatives, I found one that seemed to work. You can use Array.prototype.__defineGetter__
in the following way:
Array.prototype.__defineGetter__("sum", function sum(){
var r = 0, a = this, i = a.length - 1;
do {
r += a[i];
i -= 1;
} while (i >= 0);
return r;
});
var asdf = [1, 2, 3, 4];
asdf.sum; //returns 10
Worked for me in Chrome and Firefox.