3

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());

1
  • 1
    You can't call a function without calling a function, in general, though you might want to look at using property getter functions (in newer JavaScript interpreters only). edit see @pimvdb's answer :-) Commented Jun 6, 2012 at 14:11

3 Answers 3

12

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.)

Sign up to request clarification or add additional context in comments.

11 Comments

+1. If I'm not wrong, it's not fully cross browser supported.
Is that ES5/6? I've never heard of this. It's awesome though.
@FlorianMargaine. goggle javascript getter.
@gdororn: Very true, good point. @ Florian Magazine: ES5 specs are here.
@FlorianMargaine. You should learn how to google things about javascript. you add an MDN prefix... Example
|
2

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');

Comments

0

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.

2 Comments

This is basically equivalent to var xvar = $('#y').width();. It won't run the function on access.
Yeah, that just assigns the return value in the first place. You wouldn't get an updated version of width with that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.