Scope-ka waa halbeeg muhiim u ah fahamka sida barnaamijyada JavaScript u maamulaan xogtooda ama u isticmaalaan kala duwanaha (variables). Waxaa jira saddex nooc oo scope ah: Global scope, function scope, iyo block scope.
1. Global Scope
Scope - Global, function, and block scope |
Global scope waa meel kasta oo barnaamijkaaga ka dhex shaqeyn karta. Markaad ku qorto variable meel ka baxsan function ama block, waxaa loo yaqaanaa global variable, waxaana laga heli karaa barnaamijka oo dhan. Tusaale ahaan, haddii aad qorto
var
ama let
meel ka baxsan function, waa global variable oo waxaa la heli karaa meel kasta oo barnaamijka ah.javascript
let name = "Ali"; // Global scope
function greet() {
console.log(name); // Waa heli karaa name maxaa yeelay waa global
}
greet(); // waxay soo bandhigaysaa "Ali"
2. Function Scope
Variable-yaasha lagu qeexo function dhexdiisa waxay leeyihiin function scope, waxayna diyaar u yihiin oo keliya gudaha function-kaas. Lama heli karo variable-kaas dibadda function-ka. Taasi waxay ka ilaalinaysaa in xogtaas ay waxyeeleeyaan ama saameyn ku yeeshaan meelaha kale ee barnaamijkaaga.
javascript
function sayHello() {
let message = "Hello, World!";
console.log(message); // Waxaa lagu soo bandhigaa gudaha function-ka
}
sayHello();
console.log(message); // Error, maxaa yeelay message wuxuu leeyahay function scope
3. Block Scope
Block scope waa markasta oo aad ku qorto variable gudaha {}
sida loo isticmaalo if
, for
, ama while
. Variable-yada lagu qeexo let
ama const
gudaha block waxay leeyihiin block scope. Variable-yadaas ma heli kartid dibadda block-gaas. Waxay si gaar ah ugu fiican tahay marka aad rabto inaad xakameyso goobaha laga isticmaali karo xogtaada.
javascript
if (true) {
let age = 25; // Block scope
console.log(age); // Waxaa lagu soo bandhigaa gudaha block
}
console.log(age); // Error, maxaa yeelay age wuxuu leeyahay block scope
Gunaanad
Fahamka scope-ka JavaScript wuxuu kaa caawinayaa inaad si wanaagsan u maamusho xogta barnaamijkaaga, inaad ilaaliso xogta muhiimka ah, iyo inaad si fiican ugu isticmaasho memory-ga. Global scope waa meel kasta oo laga heli karo, function scope waa gudaha function-ka, iyo block scope waa gudaha block-ka