JavaScript - Gültigkeit von Variablen (Scope): Unterschied zwischen den Versionen
Aus Wikizone
| Zeile 9: | Zeile 9: | ||
'''Beispiele''' | '''Beispiele''' | ||
| + | <pre> | ||
global1 = 'one' | global1 = 'one' | ||
var global2 = 'two' | var global2 = 'two' | ||
| Zeile 16: | Zeile 17: | ||
obj = {local2 : "local two"} | obj = {local2 : "local two"} | ||
} | } | ||
| + | </pre> | ||
To make the variable global, one solution is to declare the variable in global scope | To make the variable global, one solution is to declare the variable in global scope | ||
<pre> | <pre> | ||
Aktuelle Version vom 24. September 2020, 17:22 Uhr
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')