Am messing around with prototypes to get a better understanding of how they work. I can't work out why I can't call hideHeader, whereas I can access a variable (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';
}
Am messing around with prototypes to get a better understanding of how they work. I can't work out why I can't call hideHeader, whereas I can access a variable (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';
}
Share
Improve this question
edited Mar 21, 2018 at 5:16
Glenn Ferrie
10.4k3 gold badges44 silver badges76 bronze badges
asked May 17, 2015 at 19:51
AlexAlex
1771 silver badge7 bronze badges
1
-
2
Observe what happens when you move the call to
App()
at the bottom, and also note thatdocument.write
overwrites the document – adeneo Commented May 17, 2015 at 19:57
2 Answers
Reset to default 9You should reorder your code so that you define hideHeader
before you try to invoke it.
Like this:
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 is an interpreted language, it's not piled. It is evaluated sequentially as it is loaded into memory.
You just need to change the order of how you are doing things. For example:
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>