2012-11-29 43 views
1

如果我想訪問它自己內部的一個值(一個對象),我該如何去做呢?如何在自己的對象中訪問某些東西?

這裏是我所(簡化):

options = { 
    'image' : { 
     'height' : { 
     'upper' : 100, 
     'lower' : 25 
     }, 
     'width' : { 
     'upper' : 100, 
     'lower' : 25 
     }, 
    'dimensions' : (Math.floor(Math.random() * (options.image.height.upper - options.image.height.lower) + options.image.height.lower)) + 'x' +               (Math.floor(Math.random() * (options.image.width.upper - options.image.width.lower) + options.image.width.lower())), 
     'color' : 'fff' 
}; 

如果你看一下options.dimensions,我試圖訪問高度和寬度的數值,但我相信我的範圍是錯誤的。

有沒有一種方法可以訪問我所需要的方式?如果沒有,那麼有什麼更好的辦法呢?

謝謝:)

+0

對不起,格式不佳。 – Will

+0

'this.image.height'工作嗎? – jahroy

+0

'this'將不起作用,因爲它指向方法的作用域 –

回答

4

做的兩個步驟:

options = { 
    'image' : { 
     'height' : { 
      'upper' : 100, 
      'lower' : 25 
     }, 
     'width' : { 
      'upper' : 100, 
      'lower' : 25 
     }, 
     'color' : 'fff' 
    } 
}; 

options.dimensions = (Math.floor(Math.random() * 
    (options.image.height.upper - options.image.height.lower) + options.image.height.lower)) + 
    'x' + (Math.floor(Math.random() * (options.image.width.upper - options.image.width.lower) + 
    options.image.width.lower())); 
1

你爲什麼不嘗試

options = { 
    'image' : { 
     'height' : { 
     'upper' : 100, 
     'lower' : 25 
     }, 
     'width' : { 
     'upper' : 100, 
     'lower' : 25 
     }, 
     'color' : 'fff' 
}; 

options['dimensions'] = (Math.floor(Math.random() * (options.image.height.upper - options.image.height.lower) + options.image.height.lower)) + 'x' + (Math.floor(Math.random() * (options.image.width.upper - options.image.width.lower) + options.image.width.lower())); 

我不認爲有什麼辦法可以參照的對象,仍然沒有創建。

相關問題