jadreymis
jadreymis

Reputation: 79

How can I access variables in a function from the global scope?

I can’t access variables in a function from the global scope. Normally I can access variables in the other function.

How can I use the str variable in the following code in the global scope?

 <html>
 <script>
 function myf(){
 str = "Change";
 document.write(str); 
 }
 document.write(str); // can not access str
 </script>
 <input type="button" value="OPEN" onclick="myf();">
 </html>

Upvotes: 0

Views: 62

Answers (2)

Halcyon
Halcyon

Reputation: 57709

Declare str globally to explicitly set it's scope.

var str;
function myf(){
  str = "Change";
  document.write(str); 
}
myf();
document.write(str); // can access str

Keep in mind that without the call to myf() the value of str remains undefined.

In general, you don't want to modify global variables inside a function because of dependency issues. Consider something like:

function myf() {
  return "Change";
}
document.write(myf());

Or if you need state:

function myf() {
  var state = "Change";
  return {
    get_state: function () {
      return state;
    },
    set_state: function () {
      //
    }
  }
}

var f = myf();
document.write(f.get_state());

Upvotes: 1

Quentin
Quentin

Reputation: 943209

The way you are doing … except that you have to run the code in the right order.

Currently you are:

  1. Defining (but not running) a function that sets str and writes it to the document (deleting the existing document in the process)
  2. Trying to use that variable
  3. Clicking on a button which runs that function and gives the variable a value

You have to swap the order of the last two tasks … and stop using document.write inside the function.

It is also good practise (and required in JavaScript strict mode) to declare your variables before you use them. You should put var str at the top of your script.

Upvotes: 0

Related Questions