Any way to define getters for lazy variables in Javascript arrays?
Posted
by LLer
on Stack Overflow
See other posts from Stack Overflow
or by LLer
Published on 2010-06-01T19:17:27Z
Indexed on
2010/06/01
19:23 UTC
Read the original article
Hit count: 180
I'm trying to add elements to an array that are lazy-evaluated. This means that the value for them will not be calculated or known until they are accessed. This is like a previous question I asked but for objects.
What I ended up doing for objects was
Object.prototype.lazy = function(var_name, value_function) {
this.__defineGetter__(var_name, function() {
var saved_value = value_function();
this.__defineGetter__(var_name, function() {
return saved_value;
});
return saved_value;
});
}
lazy('exampleField', function() {
// the code that returns the value I want
});
But I haven't figured out a way to do it for real Arrays. Arrays don't have setters like that. You could push a function to an array, but you'd have to call it as a function for it to return the object you really want. What I'm doing right now is I created an object that I treat as an array.
Object.prototype.lazy_push = function(value_function) {
if(!this.length)
this.length = 0;
this.lazy(this.length++, value_function);
}
So what I want to know is, is there a way to do this while still doing it on an array and not a fake array?
© Stack Overflow or respective owner