2015-05-17 25 views
12

Mi sto cazzando con i prototipi per capire meglio come funzionano. Non riesco a capire il motivo per cui non posso chiamare hideHeader, mentre posso accedere a una variabile (this.header.el)Comprensione di JavaScript Prototipi

function App() { 
    this.init(); 
    this.el = document.getElementById('box'); 
} 

App.prototype.init = function() { 
    document.write('hello world'); 

    this.header = new Header(); 

    this.header.hideHeader(); 
    this.header.el.style.display = 'none'; 
}; 

new App(); 

function Header() { 
    this.el = document.getElementById('header'); 
} 

Header.prototype.hideHeader = function() { 
    this.el.style.display = 'none'; 
} 
+2

osservare ciò che accade quando si sposta la chiamata a 'App()' in basso, e anche notare che 'document.write' sovrascrive il documento – adeneo

risposta

8

Si dovrebbe riordinare il codice in modo che si definirehideHeader prima di provare a invocalo.

Ti piace questa:

function App() { 
    this.init(); 
    this.el = document.getElementById('box'); 
} 

function Header() { 
    this.el = document.getElementById('header'); 
} 

Header.prototype.hideHeader = function() { 
    this.el.style.display = 'none'; 
} 

App.prototype.init = function() { 
    document.write('hello world'); 

    this.header = new Header(); 

    this.header.hideHeader(); 
    this.header.el.style.display = 'none'; 
}; 

new App(); 

JavaScript è un linguaggio interpretato, non è compilato. Viene valutato in sequenza mentre viene caricato in memoria.

+9

Ciò è dovuto al funzione di sollevamento - 'Header' è issato, ma non' hideHeader'. –

+0

Penso di vedere ora, grazie per il tuo aiuto! – Alex

+0

sono felice di aiutare. Penso che dovresti definire init come parte della funzione App e non nel prototipo. Penso che renderà il tuo codice un po 'più pulito. –

3

Hai solo bisogno di cambiare l'ordine di come stai facendo le cose. Per esempio:

function App() { 
 
    this.init(); 
 
    this.el = document.getElementById('box'); 
 
} 
 

 

 
function Header() { 
 
    this.el = document.getElementById('header'); 
 
} 
 

 
Header.prototype.hideHeader = function() { 
 
    this.el.style.display = 'none'; 
 
} 
 

 
App.prototype.init = function() { 
 
    document.write('hello world'); 
 

 
    this.header = new Header(); 
 

 
    this.header.hideHeader(); 
 
    this.header.el.style.display = 'none'; 
 
}; 
 

 
new App();
<div id="header"></div> 
 
<div id="box"></div>

Problemi correlati