admin管理员组文章数量:1430592
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>
本文标签: Understanding how JavaScript Prototypes workStack Overflow
版权声明:本文标题:Understanding how JavaScript Prototypes work - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745535934a2662269.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论