0

How do I use a variable from one function in another? I know this has been asked and answered, but I was unable to apply those solutions to my specific code. Accessing variables from other functions without using global variables How to get a variable returned across multiple functions - Javascript/jQuery I'm using a library called MP3RecorderJS at https://github.com/icatcher-at/MP3RecorderJS. On the demo html page is the following code:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>MP3 Recorder test</title>
</head>
<body id="index" onload="">

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="mp3recorder.js"></script>
<script type="text/javascript">
var audio_context;

function __log(e, data) {
  log.innerHTML += "\n" + e + " " + (data || '');
}

$(function() {

  try {
    // webkit shim
    window.AudioContext = window.AudioContext || window.webkitAudioContext;
    navigator.getUserMedia = ( navigator.getUserMedia ||
                     navigator.webkitGetUserMedia ||
                     navigator.mozGetUserMedia ||
                     navigator.msGetUserMedia);
    window.URL = window.URL || window.webkitURL;

    var audio_context = new AudioContext;
    __log('Audio context set up.');
    __log('navigator.getUserMedia ' + (navigator.getUserMedia ? 'available.' : 'not  present!'));
  } catch (e) {
    alert('No web audio support in this browser!');
  }

  $('.recorder .start').on('click', function() {
    $this = $(this);
    $recorder = $this.parent();

    navigator.getUserMedia({audio: true}, function(stream) {
      var recorderObject = new MP3Recorder(audio_context, stream, { statusContainer:  $recorder.find('.status'), statusMethod: 'replace' });
      $recorder.data('recorderObject', recorderObject);

      recorderObject.start();
    }, function(e) { });
  });

  $('.recorder .stop').on('click', function() {
    $this = $(this);
    $recorder = $this.parent();

    recorderObject = $recorder.data('recorderObject');
    recorderObject.stop();

    recorderObject.exportMP3(function(base64_mp3_data) {
      var url = 'data:audio/mp3;base64,' + base64_mp3_data;
      var au  = document.createElement('audio');

      au.controls = true;
      au.src = url;
      $recorder.append(au);

      recorderObject.logStatus('');
    });

  });

});
</script>

<div class="recorder">
  Recorder 1
  <input type="button" class="start"  value="Record" />
  <input type="button" class="stop" value="Stop" />
  <pre class="status"></pre>
</div>

<div class="recorder">
  Recorder 2
  <input type="button" class="start"  value="Record" />
  <input type="button" class="stop" value="Stop" />
  <pre class="status"></pre>
</div>

<pre id="log"></pre>
</body>
</html>

On line 56, there is the variable var url = 'data:audio/mp3;base64,' + base64_mp3_data;

If I write a new function like:

function testing() {
console.log(url)
}

How do I get var url into my "testing" function? To get it to work, I made a hidden div, made the innerhtml equal var url, and then referenced that div in my second function. But that seems pretty hackish.

Community
  • 1
  • 1
user3080392
  • 1,194
  • 5
  • 18
  • 35
  • 1
    Is there a reason you couldn't just pass it to the new variable in the standard way, for example `function testing(url)` and `testing(url);`? – Nerixel Dec 03 '14 at 03:50
  • The general answer is that you pass arguments to your function, you return variables from functions, you create common functions that can be called from multiple places or you create objects with properties and pass those objects (and many other programming techniques). – jfriend00 Dec 03 '14 at 03:52
  • I just tried to follow the first suggestion by Nerixel, but I'm getting "ReferenceError: testing is not defined" in my console log. – user3080392 Dec 03 '14 at 04:18
  • make a function like suggested by @Nerixel at the top of the script before any other script than pass `url` parameter as an argument in it. – Bhargav Modi Dec 03 '14 at 04:38
  • I just put the function above all the other script enclosed in its own script tags and I'm still getting an undefined error. – user3080392 Dec 03 '14 at 04:48

1 Answers1

-1

Simply declare the variable outside your function, like this:

var url;

then, when you update the variable in your function, its value will simply be updated, and it will be available other functions.

var hello;

function changeVar() {

  hello = 'hello';

}

function displayVar() {

  alert(hello);

}
<button onclick="changeVar()">Change the variable to "hello"</button>
<br/>
<button onclick="displayVar()">Display the variable's value</button>
Ian Hazzard
  • 7,661
  • 7
  • 34
  • 60
  • Recommending global variables is rarely the best option. – jfriend00 Dec 03 '14 at 04:01
  • ANd why is that, @jfriend00? – Ian Hazzard Dec 03 '14 at 04:03
  • Good Javascript design (and actually good design in most programming languages) uses as few global variables as possible and encapsulates data in objects and passes it as arguments whenever possible. Often when some persistent state must be kept, it can be enclosed in a closure. All this prevents unintended conflicts between different pieces of code and encourages good, safe data design. – jfriend00 Dec 03 '14 at 04:06
  • Umm. Ok. I'm going to trust you on that because of your high rep :) – Ian Hazzard Dec 03 '14 at 04:07
  • Here's some reading: [Javascript best practices](http://www.w3.org/wiki/JavaScript_best_practices#Avoid_globals), [How and Why to Avoid Globals](https://gist.github.com/hallettj/64478), [Javascript anti-patterns](http://www.htmlgoodies.com/beyond/javascript/three-javascript-anti-patterns-and-how-to-avoid-them.html), [Avoid cluttering global namespace](http://www.javascripttoolbox.com/bestpractices/#namespace) – jfriend00 Dec 03 '14 at 04:09