Javascript - 是否存在具有 self 更新值的变量?

标签 javascript jquery image

我正在尝试创建一个变量,无论何时调用它都会返回当前值。示例应该可以更好地描述这一点:

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/

相关文章:

javascript - 仅使用 JavaScript 捕获 ESC 键

javascript - jQuery 验证和客户端事件

Android 将图库文件夹中的图像复制到 SD 卡替代文件夹中

javascript - 变灰并使用 jquery 使文本框只读

javascript - 如何在 Protractorjs Spec.js 文件中实现 IF 语句?

javascript - jQuery .children() 方法返回 'undefined' ?

django - 新手应该有的现实期望是什么?

javascript - 上传前的图片高宽

html - 如果图像宽度 = 250 CSS

javascript - 选择动态插入的 HTML 元素来改变一个简单的 CSS 规则