我有这段代码:
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未定义1
它在上面定义。为什么错误?请解释一下。
答案 0 :(得分: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;
},
...
}
}