我正在尝试创建一个变量,无论何时调用它都会返回当前值。示例应该可以更好地描述这一点:
var image = jQuery('.myimage');
var currentWidth = function(){ return image.width(); };
// now, in any later place in the script the above variable
// should contain the current width without necessity to update this
// variable over and over again each time (we assume that the width
// of an image is changing as the script executes and this variable
// should always contain the CURRENT width and not the one set at the
// beginning).
因此,每当宽度发生变化时,我都希望能够获取当前宽度。这样的事情可能吗?上面的示例为我返回一个字符串,而不是当前值。
最佳答案
没有变量这样的东西,当在表达式中询问时,会导致代码被评估(即函数调用),但可以使用 getter 定义对象属性访问属性时调用的函数。
var obj = {};
Object.defineProperty(obj, "dyn", {
get: function() {
return new Date().getTime(); // just an example
}
});
每次引用 obj.dyn
时,该值都将是当前时间戳。
关于Javascript - 是否存在具有 self 更新值的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15884729/