2017-05-03 70 views
1

我有這樣的代碼:我正在爲什麼我得到ReferenceError:_variable沒有定義?

sw = {} 
sw.photoswipe = { 
    settings: { 
    screenWidths: [1024, 1280, 1440, 1680, 1920, 2560, 2880, 3840], 
    screenHeights: [ 768, 800, 900, 1050, 1200, 1600, 1800, 2400], 

    _pixelRatio: window.devicePixelRatio || 1, 

    // this line is where the error happens 
    _screenWidth: window.screen.width * _pixelRatio, 

    _screenHeight: window.screen.height * _pixelRatio, 

    getScreenSizeDescription: function() { 
     return _screenWidth.toString() + 'x' + _screenHeight; 
    }, 
    ... 
    } 
} 

錯誤是:

12:37:09.471 ReferenceError: _pixelRatio is not defined 1

它是正確的上述定義。爲什麼錯誤?請解釋。

回答

2

因爲它不存在。您必須將其分配給對象外的變量。您可以在對象之外使用sw.photoswipe.settings._pixelRatio,但在對象內部它不存在,直到創建對象。

嘗試將對象之前創建變量:

var _pixelRatio = window.devicePixelRatio || 1; 
var sw = {} 
sw.photoswipe = { 
    settings: { 
     screenWidths: [1024, 1280, 1440, 1680, 1920, 2560, 2880, 3840], 
     screenHeights: [ 768, 800, 900, 1050, 1200, 1600, 1800, 2400], 

     _pixelRatio: _pixelRatio, 

     // this line is where the error happens 
     _screenWidth: window.screen.width * _pixelRatio, 

     _screenHeight: window.screen.height * _pixelRatio, 

     getScreenSizeDescription: function() { 
      return _screenWidth.toString() + 'x' + _screenHeight; 
     }, 
     ... 
    } 
} 
相關問題