[js]Public variable wordt niet geset bij laden

Pagina: 1
Acties:

Onderwerpen


Acties:
  • 0 Henk 'm!

  • Megamind
  • Registratie: Augustus 2002
  • Laatst online: 10-09 22:45
Beetje lastige titel, maar ik heb een functie geschreven in JS:
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script type="text/javascript">
//<![CDATA[
    Test = new function()
    {
        this.public_var = 'leeg';
        
        this.init = function()
        {
            alert(this.public_var);
        }
    }
    
    Test.public_var = 'test';
    window.onload = Test.init;
    alert(Test.public_var);
//]]>
</script>
<a href="#" onclick="Test.init();">test</a>

Nu krijg ik 2x een message, 1x met "test" en dan met "undefined".

Klik op de link, krijg ik netjes "test" te zien.

Waarom pakt de init niet direct de variable op die ik meegeef?

Acties:
  • 0 Henk 'm!

  • crisp
  • Registratie: Februari 2000
  • Laatst online: 09:58

crisp

Devver

Pixelated

Omdat je in het ene geval de functie in de global scope uitvoert, en in het andere geval in de scope van Test zelf.

Intentionally left blank


Acties:
  • 0 Henk 'm!

  • Megamind
  • Registratie: Augustus 2002
  • Laatst online: 10-09 22:45
Maar hoe komt het dan dat de variable na afloop wel geset is, maar na het laden nog niet?

Acties:
  • 0 Henk 'm!

  • crisp
  • Registratie: Februari 2000
  • Laatst online: 09:58

crisp

Devver

Pixelated

Omdat (Test.init)() niet hetzelfde is als Test.init()
Je zou dus dit moeten doen dan:
JavaScript:
1
2
3
4
window.onload = function()
{
  Test.init();
}

Intentionally left blank


Acties:
  • 0 Henk 'm!

Verwijderd

Megamind schreef op zondag 24 augustus 2008 @ 19:21:
Maar hoe komt het dan dat de variable na afloop wel geset is, maar na het laden nog niet?
Omdat het twee verschillende variabelen zijn.
JavaScript:
1
window.onload = Test.init;

Dit betekent niet dat Test.init() wordt uitgevoerd bij de window.onload event. Dit betekent dat de Test.init functie de handler wordt van dat event. En dat betekent natuurlijk weer dat this in die functie niet wijst naar Test maar naar window. Dus:
JavaScript:
1
2
3
4
5
6
7
8
9
10
11
12
13
Test = new function() // creeer het object
{
    this.public_var = 'leeg'; // zet de public property
    
    this.init = function()
    {
        alert(this.public_var);
    }
}

Test.public_var = 'test'; // zet de public opnieuw
window.onload = Test.init; // voert init uit in global scope (geeft undefined)
alert(Test.public_var); // is nog steeds "test"

Wat jij zoekt is dit:
JavaScript:
1
window.onload = function() { Test.init(); };

Acties:
  • 0 Henk 'm!

  • Megamind
  • Registratie: Augustus 2002
  • Laatst online: 10-09 22:45
Ah ok nou snap ik het :) Die onload was natuurlijk fout gedefineerd, het moet zijn zoals jullie zeggen, mijn stomme fout 8)7
Pagina: 1