JavaScript - Gültigkeit von Variablen (Scope)
Aus Wikizone
Globale Variablen
- Definiert außerhalb einer Funktion egal ob mit oder ohne var
- Definiert innerhalb einer Funktion ohne var. Wenn eine Variable das erste mal aufgerufen wird ist sie automatisch global (außer im Strict Mode)
Lokale Variablen
- Definiert innerhalb einer Funktion mit var
- Variablen in Objektzuweisungen (Objektliterale)
obj = {test : "Meine Test Variable"}
Beispiele
global1 = 'one'
var global2 = 'two'
function myFunction(){
global3 = 'three'
var local1 = 'local one'
obj = {local2 : "local two"}
}
To make the variable global, one solution is to declare the variable in global scope
var a_href;
jQuery(function(){
$('sth a').on('click', function(e){
a_href = $(this).attr('href');
console.log(a_href);
//output is "home"
e.preventDefault();
}
})
another is to set the variable as a property of the window object
window.a_href = $(this).attr('href')