I was trying to understand Function Scope vs Gobal Scope, with the below example:
<script>
// The following variables are defined in the global scope
var num1 = 2,
num2 = 3,
name = "Chamahk";
// This function is defined in the global scope
function multiply() {
return num1 * num2;
}
console.log(multiply()); // Returns 60
// A nested function example
function getScore () {
var num1 = 20,
num2 = 30;
function add() {
var num1 = 200,
num2 = 300;
return name + " scored " + (num1 * num2);
}
return add();
}
console.log(getScore()); // Returns "Chamahk scored 60000"
</script>
I googled and found that Global Scoped variable can be accessed using this. changing the return code to
return name + " scored " + (this.num1 * this.num2);
gave output as "Chamahk scored 6", means this is accessing the global var num1 and num2.
This is clear, but what i wanted to know, how to access the num1 and num2 declared in getScore() function .i.e. to get the output as 600.