11

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';
}
1
  • 2
    Observe what happens when you move the call to App() at the bottom, and also note that document.write overwrites the document Commented May 17, 2015 at 19:57

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is due to function hoisting - Header is hoisted, but not hideHeader.
i'm happy to help. I think you should define init as part of the App function and not in the prototype. I think it will make your code a little cleaner.
3

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.