Omfång
Svep för att visa menyn
Ett scope är helt enkelt ett område i koden där en variabel kan nås eller användas.
Det finns två typer av scope:
- Globalt scope;
- Lokalt scope.
Om en variabel är definierad inuti ett kodblock (mellan klamrar {}), sägs den ha ett lokalt scope. Detta innebär att den endast kan nås från insidan av den funktionen eller kodblocket, eller från några nästlade block:
123456789101112function exampleFunc() { let exampleVariable = 10; console.log(exampleVariable); // Valid if(10 + 10 == 20) { console.log(exampleVariable); // Valid } } exampleFunc(); console.log(exampleVariable); // Shows error
En variabel som är definierad utanför någon kodblock sägs ha ett Globalt omfång, och den kan nås från var som helst:
123456789101112let exampleVariable = 10; function exampleFunc() { console.log(exampleVariable); // Valid if(10 + 10 == 20) { console.log(exampleVariable); // Valid } } exampleFunc(); console.log(exampleVariable); // Valid
En variabel som är definierad i ett lägre (nästlat) omfång kan inte nås från ett högre (föräldra)omfång:
function exampleFunc() {
if (10 + 10 == 20) {
let exampleVariable = 10;
console.log(exampleVariable);
// Output: 10
// The variable is defined in this block, so it is accessible here
}
console.log(exampleVariable);
// ReferenceError: exampleVariable is not defined
// The variable was defined inside the if-block and is not accessible outside it
}
exampleFunc();
console.log(exampleVariable);
// This line will never execute because the script stops after the first ReferenceError
Detta exempel innehåller avsiktliga fel för att illustrera hur variabelns räckvidd fungerar. Om koden körs skulle exekveringen stoppas efter det första felet, så kodsnutten visas endast i förklarande syfte.
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal