Reputation: 179
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
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
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
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