简体   繁体   中英

how to access global variable from function in javascript

I am trying to access global variable from function, i want to call variable outside from inside function variable.This is what I tried. Note: the query function should be work after click on query function from html drop down selection. Thank you for helping.

HTML
<select  name="myInput" id="choice1">
       <li><option value="6011">apib_cadastral:bivel</option></li>
       <li><option value="6012">apib_cadastral:burhchaura</option></li>
 </select>

javascript
var layer_name;
function query() {
  var text_value = document.getElementsByName('myInput')[0];
  var layer_name = text_value.options[text_value.selectedIndex].text;
}
query();
var config = {
  geojson: layer_name,
};

Remove the "var" inside the function. With that you define a new variable that exists inside the function.

You should change your code in this way. Because, when you re-declare variable inside query() it will occupy another cell from memory with different address. And, variable inside config object cannot access it. It will access layer_name [first defined] which contains undefined value

var layer_name ;
function query() {
    var text_value = document.getElementsByName('myInput')[0]
    layer_name = text_value.options[text_value.selectedIndex].text;
}
query();
var config = {
geojson: layer_name
}

In addition to other answers, which correctly state that you should remove var from the variable declaration inside the query() function, you could change the function to return the value, rather than relying on shared/global state.

function query() {
  var text_value = document.getElementsByName('myInput')[0];
  return text_value.options[text_value.selectedIndex].text;
}

var config = {
  geojson: query()
};

Note that this may have a performance impact depending on how many times you call query() as the return value would have to be computed each time, but it's worth considering from the perspective of alleviating the need for shared/global state.

Also note, consider replacing var with more modern const and let ...

  • const when the variable is initialised and never needs to change.
  • let when the variable needs to change beyond initialisation.
function query() {
  const text_value = document.getElementsByName('myInput')[0];
  return text_value.options[text_value.selectedIndex].text;
}

const config = {
  geojson: query()
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM