2015-05-17 9 views
12

प्रोटोटाइप के साथ गड़बड़ कर रहा हूं ताकि वे कैसे काम कर सकें। मैं बाहर काम नहीं कर सकते कारण है कि मैं hideHeader फोन नहीं कर सकते हैं, जबकि मैं एक चर (this.header.el) का उपयोग कर सकतेजावास्क्रिप्ट प्रोटोटाइप को समझना

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

का निरीक्षण करें जब आप नीचे स्थित 'अनुप्रयोग() करने के लिए कॉल के लिए कदम', और यह भी ध्यान दें कि 'document.write' दस्तावेज़ – adeneo

उत्तर

8

तुम इतनी है कि आप इससे पहले कि आप करने की कोशिश hideHeader परिभाषित अपने कोड को पुन: व्यवस्थित करना चाहिए इसे बुलाओ

इस तरह:

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(); 

जावास्क्रिप्ट एक व्याख्या की भाषा है, यह संकलित नहीं किया गया है। यह अनुक्रमिक रूप से मूल्यांकन किया जाता है क्योंकि यह स्मृति में लोड होता है।

+9

इस की वजह से है अधिलेखित कर देता है कि क्या होता है फंक्शन होस्टिंग - 'हेडर' फहराया गया है, लेकिन 'छुपा हैडर' नहीं। –

+0

मुझे लगता है कि अब मैं देख रहा हूं, आपकी मदद के लिए धन्यवाद! – Alex

+0

मुझे मदद करने में खुशी है। मुझे लगता है कि आपको ऐप फ़ंक्शन के हिस्से के रूप में इनिट को परिभाषित करना चाहिए और प्रोटोटाइप में नहीं। मुझे लगता है कि यह आपके कोड को थोड़ा क्लीनर बना देगा। –

3

आपको बस चीजों को करने के तरीके को बदलने की आवश्यकता है। उदाहरण के लिए:

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>

संबंधित मुद्दे