DeaDEnD DeaDEnD - 24 days ago 7
Javascript Question

How do I compute a variable in JavaScript if and only if it is used?

This is what I'm doing right now.

var foo = function() {
var x = someComplicatedComputationThatMayTakeMoreTime();
this.foo = function() { return x; };
return x;
}


It works but only if foo is called as a function like so

foo();


But what if I want to call it as a normal variable with a value? I could modify the code to be

var foo = function() {
var x = someComplicatedComputationThatMayTakeMoreTime();
this.foo = x;
return x;
}


That would allow me to only call it once as a function and after that as a regular variable. But it's still not what I want. Plus it gets complicated if it accidentally gets called as a function again, returning an error.

Is this even possible in JavaScript?

BTW, this is for a Chrome/Firefox extension, so IE compatibility does not matter.

Ended up using toString because getters don't allow me to redefine the whole attribute, a function must be associated with it. And toString has cleaner syntax.

Answer

How about using toString?

var foo = function() {
  function someComplicatedComputationThatMayTakeMoreTime() {
        //your calculations
  }
  return {
      toString: function() { 
           return someComplicatedComputationThatMayTakeMoreTime(); 
      }
  }
}

More about Object-to-Primitive Conversions in JavaScript

EDIT based on comment. Use a singleton (I think it's called):

myObject.prop = (function(){ 
                  function someComplicatedComputationThatMayTakeMoreTime() {
                   //your calculations
                  }
                  return { 
                    toString: function() { 
                     return someComplicatedComputationThatMayTakeMoreTime(); 
                    } 
                  } 
                })()