Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 707
fent Avatar asked Apr 24 '10 05:04

fent


2 Answers

If only Internet Explorer didn't exist, you could use getters and setters as described by John Resig in this blog article:

  • John Resig: JavaScript Getters and Setters

... They allow you to bind special functions to an object that look like normal object properties, but actually execute hidden functions instead.

like image 23
Daniel Vassallo Avatar answered Oct 01 '22 10:10

Daniel Vassallo


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(); 
                    } 
                  } 
                })()
like image 168
KooiInc Avatar answered Oct 01 '22 10:10

KooiInc