molily: Problem mit "undefiniert"

Beitrag lesen

Hallo,

text = "000120"

function Los(text) {
var t1 = text.charAt(0) + text.charAt(1) ;
var t2 = text.charAt(2) + text.charAt(3) ;
var t3 = text.charAt(4) + text.charAt(5) ;
alert(t1)
window.setTimeout("Count(t1, t2, t3)", 100);
}

Es soll also eine Funktion Count() mit t1, t2 und t3 gestartet werden.

Durch das Schlüsselwort »var« beim Notieren der Variablen t1, t2 und t3 sagst du aus, dass sie nur im Kontext der momentanen Ausführung der Funktion Los() Gültigkeit haben. Der nach dem Timeout ausgeführte Code wird aber außerhalb dieses Kontexts ausgeführt.

Wenn du beispielsweise folgende schreibst:

function meinefunktion () {
   var variable=123;
   window.setTimeout("window.alert(variable)", 100);
}
meinefunktion();

Dann findet window.alert() variable nicht (undefined).

Wenn du hingegen das »var« weglässt, sollte es klappen:

function meinefunktion () {
   variable=123;
   window.setTimeout("window.alert(variable)", 100);
}
meinefunktion();

Dasselbe gilt entsprechend für selbst erstellte Funktionen:

function funktion_a () {
   variable=123;
   window.setTimeout("funktion_b(variable)", 100);
}
function funktion_b (zahl) {
   window.alert(zahl);
}
funktion_a();

Es gibt natürlich noch komplizierte Möglichkeiten, die erlauben, weiterhin »var« zu verwenden, sofern nötig.

Mathias