JavaScript'de tanımlanan bir değişkenin kapsamı

alattin (16999) 10 yıl önce sordu

Javascript'de tanımlanan değişkenlerin kapsamı nedir? Fonksiyon içinde veya fonksiyon dışında tanımlanması farklı durumlar mıdır? Javascript'te global olarak değişken tanımlamak mümkün mü?

Javascript değişkenin fonksiyonun içinde veya dışında tanımlanması farklı durumlar midir?

Toplam 1 cevap


alattin (16999) 10 yıl önce cevapladı

Javascript değişken kapsamları ile ilgili bir örnek

// global kapsamlı değişken tanımlanması
var a=1;

// global kapsam
function one(){
    alert(a); 
}

// yerel kapsam
function two(a){
    alert(a);
}

//  tekrardan yerel kapsam
function three(){
  var a = 3;
  alert(a);
}

// Orta: javascript blok kapsamı diye bir şey yok.
function four(){
    if(true){
        var a=4;
    }

    alert(a); // alerts '4', not the global value of '1'
}


// Orta:obje özelliği
function Five(){
    this.a = 5;
}


// Gelişmiş: Kapatma
var six = function(){
    var foo = 6;

    return function(){
        // javascript "closure" means I have access to foo in here, 
        // because it is defined in the function in which I was defined.
        alert(foo);
    }
}()


// Gelişmiş: prototype-based scope resolution
function Seven(){
  this.a = 7;
}

// [object].prototype.property loses to [object].property in the lookup chain
Seven.prototype.a = -1; // won't get reached, because 'a' is set in the constructor above.
Seven.prototype.b = 8; // Will get reached, even though 'b' is NOT set in the constructor.



// These will print 1-8
one();
two(2);
three();
four();
alert(new Five().a);
six();
alert(new Seven().a);
alert(new Seven().b);