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 p
Ok, unless I misunderstood your question, I believe I have found a simple solution which does not require a so-called "lazy_push" function.
Following the method from my previous answer, you create a MyArray Class:
function MyArray(){
this.object = [];
}
MyArray.prototype.push = function(what){
this.object.push(what);
}
Now the important part is the getter function, we will create a getIdx() function to grab the value out of the array. The function then uses the 'typeof' operator to determine if the returned value is a function. If it is, return the value returned from the function, if not return the original value.
Code makes more sense:
MyArray.prototype.getIdx = function(which){
if(typeof this.object[which] == 'function'){
alert("a function");
//NOTICE THE '()' AT THE END OF THE NEXT LINE!!!
return this.object[which]();
}
return this.object[which];
}
Hopefully if I didn't completely answer your question you can figure it out from here.
<--------- My original post ------------->
Not really an answer, but a few important points.
There are no real arrays in Javascript, an Array is just an extended Object (as is everything in JS)
You should ideally never add prototype functions to the native objects in JS, you might accidentally overwrite an existing property, or create confusing errors down the line. For instance, adding to the prototype of Object is going to add to every single Object in JS (which is everything), you need to make absolutely sure that you want every type in JS to have that property. This is just dangerous because if you accidentally overwrite the actual Array() or Object() functions, you will break javascript in the browser, period, a refresh of the page won't fix it.
Rather than adding to the prototype of the Object you are modifying, create a new Object that extends it. For instance if you want to extend the Array class:
//create the constructor,
//with an object variable that holds the object you wish to extend
function MyArray(){
this.object = [];
}
//create functions which reference the native functions of the object
MyArray.prototype.push = function(what){
this.object.push(what);
}
//Etc... Etc.... Etc.....
Its not necessarily fun writing all the accessor methods for native Object functions, but it keeps the Javascript engine safe.