首页 > 解决方案 > 为什么函数在全局声明变量而不是 var 时有效

问题描述

我想声明该属性soundFileNamevar soundFileName = 'audio/60.wav';以便它soundFileName不是全局定义的,但是当我这样做时,我得到ReferenceError: soundFileName is not defined.

我将 的值soundFileName作为参数传递给loop(soundFileName),我认为该值'audio/60.wav'应该可以很好地传递。

我怀疑这与范围或嵌套有关,但我不确定如何解决这个问题。当我soundFileName = 'audio/60.wav';不使用 var 时,代码确实有效。

我错过了什么?谢谢!

编辑:代码现在工作和更新!

<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

  <script src="js/howler.core.js"></script>
  <link rel="stylesheet" href="css/styles.css">

</head>

<body>

  <script src="timeprobabilities.js"></script>

  <script>
    ///////////////////////////////////////////////////////////////
    // MASTER START ///////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////

    // initiates fist call to all clocks to each will start and can then be called again

    (function masterStart() {
      setTimeout(function() {
        //// LOOP SOUNDS \\\\
        A();
      }, 0);
    }());

    ///////////////////////////////////////////////////////////////
    // LOOPS SHARED OPTIONS ///////////////////////////////////////
    ///////////////////////////////////////////////////////////////

    var options = {
      numberOfSounds: 0,
      maxNumberOfSounds: 4
    };

    function logNumberOfSounds() { // passing options into this before is what broke code
      options.numberOfSounds++;
      //console.log('Number of sounds is: ' + options.numberOfSounds + '########');
    }

    ///////////////////////////////////////////////////////////////
    // LOOP A  ////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////

    function A() {
      var optionsA = {
        playDurationMin: 0,
        playDurationMax: 60000,
        // start time minimum and maximum
        startMinA: 0,
        startMaxA: 8000,
        maxVolumeA: 1,
        //
        startMinB: 0,
        startMaxB: 30000,
        maxVolumeB: 1,
        //
        startMinC: 0,
        startMaxC: 30000,
        maxVolumeC: 1,
        //
        startMinD: 0,
        startMaxD: 30000,
        maxVolumeD: 1,
        //
        startMinE: 0,
        startMaxE: 30000,
        maxVolumeE: 1,
        //
        startMinF: 0,
        startMaxF: 30000,
        maxVolumeF: 1,
        //
        startMinG: 0,
        startMaxG: 30000,
        maxVolumeG: 1,
        //
        startMinH: 0,
        startMaxH: 30000,
        maxVolumeH: 1,
        //
        startMinI: 0,
        startMaxI: 30000,
        maxVolumeI: 1,
        //
        startMinJ: 0,
        startMaxJ: 30000,
        maxVolumeJ: 1,
        //
        startMinK: 0,
        startMaxK: 30000,
        maxVolumeK: 1
      };

      masterClock();

      function masterClock() {
        setTimeout(function() {
          soundA(options, optionsA);
        }, 10); // these need to be called with delay so they don't use the other functions' paramaters
      }

      function soundA() {

        var soundFileName = 'audio/60.wav';
        fadeIn = 8000;
        fadeOut = 8000;

        console.log('soundFileName in A: ' + soundFileName);

        calculateStartDelay(optionsA.startMinA, optionsA.startMaxA);

        function calculateStartDelay(startMin, startMax) {
          startDelay = Math.floor(Math.random() * startMax) + startMin;
        }

        function calculatePlayDuration(playDurationMin, playDurationMax) {
          playDuration = Math.floor((Math.random() * playDurationMax) + playDurationMin);
        }

        function executePlayTools() {
          calculatePlayDuration(optionsA.playDurationMin, optionsA.playDurationMax);
          loop(options, playDuration, soundFileName, fadeIn, fadeOut);
          console.log('A: ////////////////////////////////// ');
          masterClock();
        }

        setTimeout(function() {
          if (probabilityValue < probabilityPointA) {
            maxVolume = optionsA.maxVolumeA;
            executePlayTools();
          } else if (probabilityValue < probabilityPointB) {
            maxVolume = optionsA.maxVolumeB;
            executePlayTools();
          } else if (probabilityValue < probabilityPointC) {
            maxVolume = optionsA.maxVolumeC;
            executePlayTools();
          } else if (probabilityValue < probabilityPointD) {
            maxVolume = optionsA.maxVolumeD;
            executePlayTools();
          } else if (probabilityValue < probabilityPointE) {
            maxVolume = optionsA.maxVolumeE;
            executePlayTools();
          } else if (probabilityValue < probabilityPointF) {
            maxVolume = optionsA.maxVolumeF;
            executePlayTools();
          } else if (probabilityValue < probabilityPointG) {
            maxVolume = optionsA.maxVolumeG;
            executePlayTools();
          } else if (probabilityValue < probabilityPointH) {
            maxVolume = optionsA.maxVolumeH;
            executePlayTools();
          } else if (probabilityValue < probabilityPointI) {
            maxVolume = optionsA.maxVolumeI;
            executePlayTools();
          } else if (probabilityValue < probabilityPointJ) {
            maxVolume = optionsA.maxVolumeJ;
            executePlayTools();
          } else {
            maxVolume = optionsA.maxVolumeK;
            console.log('Probability Else');
          }
          console.log('startDelay: ' + startDelay)
        }, startDelay);
      }
    }

    ///////////////////////////////////////////////////////////////
    // SHARED LOOP  ///////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////

    function loop(options, playDuration, soundFileName, fadeIn, fadeOut) {

      console.log('soundFileName in loop: ' + soundFileName);

      if (options.numberOfSounds < options.maxNumberOfSounds) { //Don't create more than the max number of sounds.

        var sound = getSound(soundFileName);
        var id2 = sound.play();

        logNumberOfSounds();

        sound.volume(0); // don't think I need this since it's declared above and in getSound(), but it stops blips?
        sound.fade(0, maxVolume, fadeIn, id2); // FADE IN

        setTimeout(function() {
          sound.fade(maxVolume, 0, fadeOut, id2); // FADE OUT
          options.numberOfSounds--;

          // Attempt to clean up the sound object
          setTimeout(function() {
            sound.stop();
            sound.unload();
          }, fadeOut + 1000);
        }, playDuration);
      }

    }

    // PLAYER FOR MAIN SOUND FUNCTION /////////////////////////////
    function getSound(soundFileName) {
      return new Howl({
        src: [soundFileName],
        autoplay: true,
        loop: true,
        volume: 0,
        fade: 0 // removes the blip
      });
    }
  </script>

  <script src="js/howler.core.js"></script>
  <script src="js/siriwave.js"></script>
  <script src="js/player.js"></script>

</body>

</html>

标签: javascriptvariablesparametersglobal-variablesvar

解决方案


每个函数都有自己的作用域,函数内声明的变量只存在于该函数的作用域内

在这种情况下,它soundFileName被声明为in,所以它只存在于 的范围var内。soundAsoundA

您将soundFileName作为参数传递给loop,并从那里将其传递给,getSound但您的函数定义不包括任何命名参数。loopgetSound

您需要更改函数定义loop包含getSound预期参数:

function loop(options, playDuration, soundFileName, fadeIn, fadeOut) {
  ...
  // soundFileName is now availabie in this scope
  ...
}


function getSound(soundFileName) {
  ...
  // soundFileName is now availabie in this scope
  ...
}

请注意,在JavaScript(不包括箭头函数)中的每个函数中,都有一个特殊的arguments对象,其中包含调用函数时使用的参数,因此,由于您soundFileName作为第三个参数传递给loop传递的值也将在loopas中可用arguments[2],并且因为它是通过的作为它的第一个参数getSound也将在getSoundas中可用arguments[0]


推荐阅读