在另一个函数中访问函数结果

时间:2014-09-30 07:16:59

标签: jquery

我有下面的函数isRetina,我试图在另一个resizeImage()内访问结果,但变量retinaCheck总是让我回复未定义。我在一开始就宣布了全局变量,为什么会这样?

 $(window).load(function () {
     function isRetina() {
         return ((window.matchMedia && (window.matchMedia('only screen and (min-resolution: 192dpi), only screen and (min-resolution: 2dppx), only screen and (min-resolution: 75.6dpcm)').matches || window.matchMedia('only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2/1), only screen and (min--moz-device-pixel-ratio: 2), only screen and (min-device-pixel-ratio: 2)').matches)) || (window.devicePixelRatio && window.devicePixelRatio > 2)) && /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
     }

     var retinaCheck = isRetina();

 });

 function resizeImage() {
     if ($(window).width() > 649) {
         console.log("resize:" + retinaCheck)

     }
 });

1 个答案:

答案 0 :(得分:0)

您可以在window.load之外声明一个全局变量,并在window.load内为其指定值。当您调用resizeImage()函数时,您可以读取retinaCheck值。

var retinaCheck;
 $(window).load(function() {
    function isRetina(){
         return ((window.matchMedia && (window.matchMedia('only screen and (min-resolution: 192dpi), only screen and (min-resolution: 2dppx), only screen and (min-resolution: 75.6dpcm)').matches || window.matchMedia('only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2/1), only screen and (min--moz-device-pixel-ratio: 2), only screen and (min-device-pixel-ratio: 2)').matches)) || (window.devicePixelRatio && window.devicePixelRatio > 2)) && /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
    }

    retinaCheck = isRetina();

});

function resizeImage() {
   if ($(window).width() > 649) {        
          console.log("resize:"+retinaCheck)            
      });
}