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.

5
  • 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);? Commented Dec 3, 2014 at 3: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). Commented Dec 3, 2014 at 3:52
  • I just tried to follow the first suggestion by Nerixel, but I'm getting "ReferenceError: testing is not defined" in my console log. Commented Dec 3, 2014 at 4: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. Commented Dec 3, 2014 at 4: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. Commented Dec 3, 2014 at 4:48

1 Answer 1

-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>

Sign up to request clarification or add additional context in comments.

5 Comments

Recommending global variables is rarely the best option.
ANd why is that, @jfriend00?
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.
Umm. Ok. I'm going to trust you on that because of your high rep :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.