2017-05-03 93 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; 
     }, 
     ... 
    } 
} 
相关问题