0

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

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).

因此,每当宽度发生变化时,我都希望能够获得当前宽度。这样的事情可能吗?上面的示例为我返回一个字符串,而不是当前值。

4

2 回答 2

2

没有变量之类的东西,当在表达式中询问时,会导致代码被评估(即函数调用),但是可以使用在访问属性时调用的 getter 函数来定义对象属性。

var obj = {};
Object.defineProperty(obj, "dyn", {
  get: function() {
    return new Date().getTime(); // just an example
  }
});

每次obj.dyn引用时,该值将是当前时间戳。

于 2013-04-08T17:04:11.090 回答
1

一般来说,您可以执行以下操作:

function currentWidth() {
   return $('.myimage').width();   // or image.width() since you have it defined, make sure there is ONLY one element returned or you will need $('.myimage:eq(0)').width()
}

你会像这样使用它:

if (currentWidth()>400) {
  // do something
}
于 2013-04-08T17:03:31.487 回答