Rakamazirem
Rakamazirem

Reputation: 179

Javascript: Use function as variable

Is there a way to use a variable name which has a function assigned to it, for example, to get the actual width of an element?

var xvar = function(){ return $('#y').width()}

And use it as

console.log(xvar);

Instead of

console.log(xvar());

Upvotes: 3

Views: 4541

Answers (3)

KooiInc
KooiInc

Reputation: 122996

As long as your function returns String or Number this could be an alternative for non-ES5 environments:

var xvar = new function(id){ 
              this.toString = 
              this.valueOf = function(){
                   return $(id).width()};
           }('#y');

Upvotes: 2

Ruben Nagoga
Ruben Nagoga

Reputation: 2218

If I not mistake it will work because xvar will store reference to result of immediately-invoked function:

var xvar = (function() { return $('#y').width(); })();
console.log(xvar);

But after it you can't use xvar() version.

Upvotes: 0

pimvdb
pimvdb

Reputation: 154968

Not with variables, but it is possible with properties on objects. It's called a getter.

var obj = {
  get xvar() { return $('#y').width(); }
};

Then you can use:

obj.xvar;  // will run the above function

(Theoretically, a way to use a variable getter is when an object's properties reflect the variables. For example, the window object.)

Upvotes: 12

Related Questions