理解JavaScript原型的工作原理

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
观察将App()调用移到底部时会发生什么,并注意document.write会覆盖文档。 - adeneo
2个回答

9

您需要重新排列代码,以便在调用它之前定义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();

JavaScript是一种解释型语言,它没有编译的过程。它在加载到内存中时会按顺序逐行执行。


9
这是由于函数提升造成的——Header 被提升了,但是 hideHeader 没有被提升。 - Sean Vieira
我很乐意帮助。我认为你应该将init定义为App函数的一部分,而不是原型中的一部分。我觉得这样会使你的代码更简洁一些。 - Glenn Ferrie

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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接