user629283
user629283

Reputation: 349

calling a prototype function repeats the wrong function

I am trying to learn about structures and anonymous functions in JavaScript and I had a looked at a lot codes or libraries who have done it this way. However when i try to follow the way they do it, it seems to call the wrong innit. Here is my code:

file 1: is called startUp;

this.project = this.project || {};

(function(){

    project.init = function (){
        console.log("startUp");
         project.Setup();

    }

}());

file 2: is called Setup

this.project = this.project || {};

(function() {

    var Setup = function() {
        this.init();
    };

    var p = Setup.prototype;

    p.init = function() {
        console.log("Setup");
    };

    project.Setup = Setup;
}());

for some reason the innit in the setup isn't being called but the start up innit is looping like crazy.

Upvotes: 0

Views: 43

Answers (1)

gen_Eric
gen_Eric

Reputation: 227280

Inside Setup, this is not what you think it is. this is set by how the function is called.

So when you do project.Setup();, the value of this inside Setup is project. So this.init() is calling project.int(). Which is calling project.Setup(); and so on, creating an infinite loop.

Setup.prototype.init will only be called if you do new Setup.

Upvotes: 2

Related Questions