Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding how JavaScript Prototypes work

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';
}
like image 586
Alex Avatar asked May 17 '15 19:05

Alex


1 Answers

You 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 compiled. It is evaluated sequentially as it is loaded into memory.

like image 143
Glenn Ferrie Avatar answered Sep 27 '22 18:09

Glenn Ferrie