0

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.

4

1 に答える 1

0

あなたの質問は少し混乱していると言わざるを得ません。

通常、関数にパラメータを使用して、値を渡します。

60000 を取得する理由は、add 関数で num1 と num2 を 200 と 300 に設定しているためです。

add 関数を変更して num1 と num2 をパラメーターとして取り、それらを再宣言しないようにすると、getScore(); で値を渡すことができます。

例 return add(num1, num2);

<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(num1, num2) {
  return num1 * num2;
}

console.log(multiply(num1, num2)); // Returns 6!!!

// A nested function example
function getScore () {
  var num1 = 20,
      num2 = 30;

  function add(num1, num2) {
    return name + " scored " + (num1 * num2);
  }

  return add(num1, num2);
}

console.log(getScore()); // Returns "Chamahk scored 60000"
</script>
于 2015-08-04T16:08:45.150 に答える