为什么函数在全局声明变量时起作用,而不是在var中起作用

问题描述 投票:1回答:3

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

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

我怀疑这与范围或嵌套有关,但我不确定如何解决问题。当我使用没有var的soundFileName = 'audio/60.wav';时,代码可以正常工作。

我错过了什么?谢谢!

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

<!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>
javascript variables parameters global-variables var
3个回答
2
投票

您没有正确使用变量的值。它的值在soundA()函数内定义,然后传递给函数loop(),它没有任何方法知道哪个变量是哪个。

这个问题有两种解决方案。设置预定义的参数名称,如function loop(options, options, playDuration, soundFileName, fadeIn, fadeOut){...}然后在函数体中使用这些名称,或者你可以使用arguments函数对象。 arguments对象是一个类似于数组的对象,它使用包含所有传递参数的所有函数(不包括箭头函数)创建,通过这些参数可以轻松使用传递给它的变量。请参阅以下示例:

loop(options, playDuration, soundFileName, fadeIn, fadeOut);

function loop() {
          console.log('soundFileName in loop: ' + arguments[2]); //The arguments object will contain all five parameters passed to the function call. 
}

话虽如此,使用未知数量的函数参数被一些人认为是不好的做法,因为它可能导致比使用预定义参数更多的错误和陷阱。尽管如此,arguments对象随时可用,您可以根据需要构建应用程序。请记住,其他人可能会阅读代码,并且一直混淆不清。

此外,在解决了这个问题之后,我面临另一个问题,即你在声明实际函数之前的单独脚本标记中使用函数,从而导致undefined错误。

另外,请将此答案标记为帮助其他人路过的解决方案。

编辑#1:从ES6 +开始,您可以指定默认参数值,以防您希望始终保持函数按预期运行,即使值未正确传递也是如此。

编辑#2:正如@nikolairiedel在评论中提到的,函数getSound()超出了该变量的声明范围,因此无法获得其值。您可以为该功能设置参数和/或指定默认参数值,以确保它在编辑#1中如上所述始终有效。


2
投票

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

在这种情况下,soundFileNamevar中被宣布为soundA,所以它只存在于soundA的范围内。

你将soundFileName作为loop的论据传递,并从那里传递给getSound,但你的function definitionsloopgetSound不包括任何命名参数。

您需要更改function definitionloopgetSound以包含预期参数:

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中的每个函数中(不包括arrow functions)都有a special arguments object,其中包含函数被调用的参数,因此,由于您将soundFileName作为第三个参数传递给loop,因此传递的值也将在loop中作为arguments[2]提供,并且因为它作为getSound的第一个参数被传递,它也将在getSound中作为arguments[0]


0
投票

也许尝试改变这一点

 function loop() {

至:

function loop(param1,param2.....){

在你的情况下:

function loop(soundFileName,playDuration, ...){
© www.soinside.com 2019 - 2024. All rights reserved.