了解JavaScript Prototypes的工作原理

Ale*_*lex 12 javascript prototype

我正在搞乱原型,以便更好地了解它们的工作原理.我无法理解为什么我不能调用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';
}
Run Code Online (Sandbox Code Playgroud)

Gle*_*rie 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();
Run Code Online (Sandbox Code Playgroud)

JavaScript是一种解释型语言,它不是编译的.它在加载到内存中时按顺序进行评估.

  • 这是由于函数提升 - "Header"被提升,但不是"hideHeader". (9认同)