JavaScript - Gültigkeit von Variablen (Scope): Unterschied zwischen den Versionen

Aus Wikizone
Wechseln zu: Navigation, Suche
 
(5 dazwischenliegende Versionen von 2 Benutzern werden nicht angezeigt)
Zeile 1: Zeile 1:
 
'''Globale Variablen'''
 
'''Globale Variablen'''
* Definiert '''außerhalb einer Funktion''' egal ob mit oder ohne var
+
* Definiert '''außerhalb einer Funktion''' egal ob '''mit oder ohne var'''
* Definiert '''innerhalb einer Funktion ohne var''', wenn diese das erste mal aufgerufen wird
+
* 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'''
 
'''Lokale Variablen'''
 
* Definiert '''innerhalb einer Funktion mit var'''
 
* Definiert '''innerhalb einer Funktion mit var'''
* Variablen in Objektzuweisungen (z.B. {test : "Meine Test Variable"} )
+
* Variablen in Objektzuweisungen (Objektliterale)
 +
obj = {test : "Meine Test Variable"}
 +
 
 +
'''Beispiele'''
 +
<pre>
 +
global1 = 'one'
 +
var global2 = 'two'
 +
function myFunction(){
 +
  global3 = 'three'
 +
  var local1 = 'local one'
 +
  obj = {local2 : "local two"}
 +
}
 +
</pre>
 +
To make the variable global, one solution is to declare the variable in global scope
 +
<pre>
 +
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')
 +
</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')