首页 > 解决方案 > 我的变量是作用域的,我需要它是全局的

问题描述

嗨,所以我是这个基本的新手,在我自己看了相当多的时间后寻求帮助。

我正在玩具编程一个游戏,我使用智能手机的方向来触发事件。我的问题是我无法获得变量值,这似乎遥不可及。如果我将函数的参数发送给彼此,游戏运行良好,但如果我需要更改全局变量以便我可以轻松使用它。

  1. 看来我的变量是作用域的,我不明白我该如何帮助它。
  2. 在下面的示例中,如何使 beta 变量成为全局变量?
  3. 变量的作用域是因为 if 语句、=> 还是 .then?
//The variable pression is the one I need to be global
let beta, gamma, pression=0, gameover=false, audio_source;

//displaying banner to authorize DeviceOrientationEvent on mobile
function bannerAuthorisation() {
   if (window.DeviceOrientationEvent && typeof window.DeviceOrientationEvent.requestPermission === 'function'){
      const banner = document.createElement('div');
      banner.innerHTML = `<div id="autorisation" style="z-index: 1; position: absolute; width: 100%; background-color:#000; color: #fff" onclick="clickRequestDeviceOrientationEvent();"><p style="padding: 10px">Cliquez ici pour autoriser l'accès à votre capteur de mouvements.</p></div>`;
      document.querySelector('body').appendChild(banner)
    } else {
      alert("Sorry you cannot play");
    }
}

//If permission to play with DeviceOrientationEvent is granted, then I fetch beta and gamma
function clickRequestDeviceOrientationEvent() {
  window.DeviceOrientationEvent.requestPermission()
      .then(response => {
        if (response === 'granted') {
            window.addEventListener('deviceorientation', (e) => {
            document.getElementById('autorisation').style.display = 'none';
            //normalizing beta and gamma values and assigning it to global variables
            beta=(Math.round(e.beta));
            gamma=(Math.round(e.gamma));
            //Here I send those values to another function and I can use it
            increasePression();
            }
          )} else {
          alert("Sorry you need to authorize the game to use it.")
      }
  })
      .catch(e => {
        console.error(e)
  })
}

//Here I try to display the beta variable in HTML and it fails
//because I did not send params from above hte function above and it seems my var is not global
function test (){
  document.getElementById("stuff").innerHTML = beta;
}

标签: javascriptvariablesscope

解决方案


推荐阅读