06 July 2023

Có bao nhiêu Scopes trong Javascript

Scope Levels

1 - Global Scope
2 - Module Scope
3 - Block Scope
4 - Function Scope




Global Scope

<script src="script.js"></script>

<script>
  // script.js
  const a = 1
  console.log(a)
  // Prints: 1
</script>

<script src="script-1.js"></script>
<script src="script-2.js"></script>

<script>
  // script-1.js

  const a = 1
  // script-2.js

  console.log(a)
  // Prints: 1
</script>

Module Scope

<script src="script-1.js" type="module"></script>
<script src="script-2.js" type="module"></script>

<script>
  // script-1.js

  const a = 1
  console.log(a)
  // Prints: 1

  // script-2.js

  console.log(a)
  // Throws Uncaught Reference Error: a is not defined
</script>

Block Scope

function test() {
  const funcVar = "Func"

  if (true) {
    const ifVar = "If"
    console.log(funcVar, ifVar)
    // Prints: "Func", "If"
  }

  console.log(funVar, ifVar)
  // Throws Uncaught Reference Error: ifVar is not defined
}

{
  const a = 10
}

console.log(a)
// Throws Uncaught Reference Error: a is not defined

Function Scope

function test() {
  var funcVar = "Func"

  if (true) {
    var ifVar = "If"
    console.log(funcVar, ifVar)
    // Prints: "Func", "If"
  }

  console.log(funVar, ifVar)
  // Prints: "Func", "If"
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang