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

Posted by LLer on Stack Overflow See other posts from Stack Overflow or by LLer
Published on 2010-04-24T05:13:47Z Indexed on 2010/04/24 5:23 UTC
Read the original article Hit count: 142

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about variables