Note that there are some explanatory texts on larger screens.

plurals
  1. POAny way to define getters for lazy variables in Javascript arrays?
    primarykey
    data
    text
    <p>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 <a href="https://stackoverflow.com/questions/2703304/how-do-i-compute-a-variable-in-javascript-if-and-only-if-it-is-used">previous question I asked</a> but for objects.</p> <p>What I ended up doing for objects was</p> <pre><code>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 }); </code></pre> <p>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.</p> <pre><code>Object.prototype.lazy_push = function(value_function) { if(!this.length) this.length = 0; this.lazy(this.length++, value_function); } </code></pre> <p>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?</p> <p>UPDATE: The following function works only if the value_function returns a primitive data type.</p> <pre><code>Array.prototype.lazy_push = function(value_function) { var a = this, i = this.length; this.push({ toString: function() { return a[i] = value_function(); } }); } </code></pre> <p>If you try to push say an object that has properties in it, you won't be able to access the properties until you access the object directly. This doesn't happen with setters, that's why I want some kind of setting syntax for Javascript. For now I will be using the fake array, which is enough for what I'm doing.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload