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?