我试图通过以下示例了解 Function Scope 与 Gobal Scope:
<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>
我搜索了一下,发现可以使用这个来访问 Global Scoped 变量。将返回码更改为
return name + " scored " + (this.num1 * this.num2);
输出为“Chamahk 得分 6”,表示这是访问全局变量 num1 和 num2。
这很清楚,但我想知道的是,如何访问在 getScore() 函数中声明的 num1 和 num2 。即获得输出为 600。