2013-04-08 58 views
0

我試圖創建一個變量,每當調用將返回當前值。示例應該更好地描述:Javascript - 是否存在具有自我更新值的變量?

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

因此,無論寬度發生什麼變化,我都希望能夠獲取當前寬度。有這樣的可能嗎?上面的例子爲我返回一個字符串,而不是當前值。

+1

這不是你所看到的行爲嗎?這就是這個代碼應該如何工作。如果不是,則應該發佈更多的上下文。 – FishBasketGordo 2013-04-08 17:03:04

+0

@FishBasketGordo他希望能夠引用「currentWidth」而不顯式地進行函數調用。 – Pointy 2013-04-08 17:08:11

回答

2

有作爲,在審訊時變量沒有這樣的事表達式,導致代碼被評估(即函數調用),但可以使用訪問屬性時調用的getter函數定義對象屬性。

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

每次引用obj.dyn時,該值都將是當前時間戳。

+0

這就是我要找的。那麼,它只能用對象而不是單個變量來自我更新? – Atadj 2013-04-08 17:06:49

+0

@Paul沒錯,只有對象屬性。變量總是隻有簡單值的變量。 – Pointy 2013-04-08 17:07:22

+0

好:)也許這對代碼組織來說更好。謝謝! – Atadj 2013-04-08 17:08:50

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 
} 
+0

謝謝!這就是我一直在尋找的:)我只是希望它可以附加到一個變量,但事實證明這是不可能的。 – Atadj 2013-04-08 17:13:44