Omfång
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:
- Global 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 inuti 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 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:
1234567891011function exampleFunc() { if(10 + 10 == 20) { let exampleVariable = 10; console.log(exampleVariable); // Valid } console.log(exampleVariable); // Shows error } exampleFunc(); console.log(exampleVariable); // Shows error
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
Can you explain the difference between global and local scope in more detail?
Why does accessing `exampleVariable` outside its scope cause an error?
Can you give more examples of variable scope in JavaScript?
Fantastiskt!
Completion betyg förbättrat till 1.33
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:
- Global 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 inuti 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 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:
1234567891011function exampleFunc() { if(10 + 10 == 20) { let exampleVariable = 10; console.log(exampleVariable); // Valid } console.log(exampleVariable); // Shows error } exampleFunc(); console.log(exampleVariable); // Shows error
Tack för dina kommentarer!