The x
variables in your eample are local to the functions in which they're declared. Once the function returns, the variable isn't present anymore.
To change that without changing your code in other ways, you'd have to make x
a global instead:
var x; // Global
function starthigh() {
x = 3;
}
function startmid() {
x = 2;
}
function startlow() {
x = 1;
}
function start() {
alert(x) /* Undefined (make this DEFINED with code only in startlow/mid/high functions) */
}
Global variables are best avoided, however, perhaps by using modern event handling:
<button id="btn1x">1x Bet</button>
<button id="btn2x">2x Bet</button>
<button id="btn3x">3x Bet</button>
<script>
(function() { // Scoping function, so its contents aren't globals
var x;
function starthigh() {
x = 3;
}
function startmid() {
x = 2;
}
function startlow() {
x = 1;
}
function start() {
alert(x) /* Undefined (make this DEFINED with code only in startlow/mid/high functions) */
}
// Hook up your handlers
document.getElementById("btn1x").addEventListener("click", function() {
starthigh();
start();
});
document.getElementById("btn2x").addEventListener("click", function() {
startmid();
start();
});
document.getelementById("btn3x").addEventListener("click", function() {
startlow();
start();
});
})();
</script>
We can take that further, though. starthigh
, startmid
, and startlow
all do the same thing, just with different values. So we could have a single function to do that thing, and perhaps a single function that called it and then called start
:
<button id="btn1x">1x Bet</button>
<button id="btn2x">2x Bet</button>
<button id="btn3x">3x Bet</button>
<script>
(function() { // Scoping function, so its contents aren't globals
var x;
function startWith(value) {
x = value;
start();
}
function start() {
alert(x) /* Undefined (make this DEFINED with code only in startlow/mid/high functions) */
}
// Hook up your handlers
document.getElementById("btn1x").addEventListener("click", startWith.bind(null 3));
document.getElementById("btn2x").addEventListener("click", startWith.bind(null 2));
document.getelementById("btn3x").addEventListener("click", startWith.bind(null 2));
})();
</script>
Or we can store the value to use on the button:
<button class="start" data-value="3">1x Bet</button>
<button class="start" data-value="2">2x Bet</button>
<button class="start" data-value="1">3x Bet</button>
<script>
(function() { // Scoping function, so its contents aren't globals
var x;
function startWithClick() {
startWith(+this.getAttribute("data-value"));
}
function startWith(value) {
x = value;
start();
}
function start() {
alert(x) /* Undefined (make this DEFINED with code only in startlow/mid/high functions) */
}
// Hook up your handlers
document.querySelectorAll(".start").forEach(function(btn) {
btn.addEventListener("click", startWithClick);
});
})();
</script>
More to explore: