1

I have this code:

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;
    },
    ...
  }
}

Error I am getting is:

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

It's defined right above. Why the error? Please explain.

Marko Avlijaš
  • 1,579
  • 13
  • 27

1 Answers1

2

Because it doesn't exist. You would have to assign it to a variable outside the object. You could use sw.photoswipe.settings._pixelRatio outside of the object, but inside the object it does not exist yet untill the object is created.

Try to create the variable before the object:

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;
        },
        ...
    }
}
Randy
  • 9,419
  • 5
  • 39
  • 56