Javascript:使用函数作为变量 [英] Javascript: Use function as variable
本文介绍了Javascript:使用函数作为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法使用分配了函数的变量名,例如,获取元素的实际宽度?
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()}
并将其用作
console.log(xvar);
代替
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(); }
};
然后你可以使用:
obj.xvar; // will run the above function
(理论上,使用变量 getter 的一种方法是当对象的属性反映变量时.例如,window
对象.)
(Theoretically, a way to use a variable getter is when an object's properties reflect the variables. For example, the window
object.)
这篇关于Javascript:使用函数作为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文