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 us
Solution 1:
Not with variables, but it is possible with properties on objects. It's called a getter.
var obj = {
getxvar() { 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.)
Solution 2:
As long as your function returns String
or Number
this could be an alternative for non-ES5 environments:
var xvar = newfunction(id){
this.toString =
this.valueOf = function(){
return $(id).width()};
}('#y');
Solution 3:
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.
Post a Comment for "Javascript: Use Function As Variable"