Alex
Alex

Reputation: 177

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';
}

Upvotes: 11

Views: 316

Answers (2)

Donal
Donal

Reputation: 32713

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>

Upvotes: 3

Glenn Ferrie
Glenn Ferrie

Reputation: 10380

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.

Upvotes: 9

Related Questions