简体   繁体   English

Javascript:使用函数作为变量

[英]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());

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.) (从理论上讲,使用变量getter的一种方法是当对象的属性反映变量时。例如, window对象。)

As long as your function returns String or Number this could be an alternative for non-ES5 environments: 只要您的函数返回StringNumber这可能是非ES5环境的替代方案:

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

If I not mistake it will work because xvar will store reference to result of immediately-invoked function: 如果我没有弄错它会工作,因为xvar将存储对立即调用函数的结果的引用:

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

But after it you can't use xvar() version. 但在它之后你不能使用xvar()版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM