Search code examples
javascriptprototypeself-executing-function

Method call from prototype self executing method


I'm trying to really get how prototype works in js. I'm currently on a little game project that is based on a loop.

I would like to have a Game object instance that will start itself once instantiated, calling a loop method it defines.

What I'm trying to get is something like this :

function Game() {};
Game.prototype = {
    start: (function() {
        this.loop();    // this is where i have a problem
    })()

    loop: function() {
        // do stuff
    }
}

Now, obviously, this doesn't work since I'm using a self executing function around start to get it launched automatically, so the 'this' keyword represents the window object, instead of the Game object.

Is there any way to do this so that I don't have to manually call the start method after I instantiated a new Game object ?

Thanks


Solution

  • function Game() { this.loop(); };
    Game.prototype={ 
    
        loop: function() {
            // do stuff
        }
    }
    
    new Game;