0

This is my first question in stackoverflow:

I have a problem with my code in Javascript. I'm new writting in this language and I don't know where is the problem in this Module, but the error is

Uncaught TypeError: Cannot read property 'init' of undefined.

I want to begin with HTML5/JS games and i'm a little nervous because this problem I have since few days.... Thank you, guys!

var game = (function() {
    //////////////////////////////////////////////////
    /////////////////Atributos del juego/////////////////
    ////////////////////////////////////////////////////////
    var canvas = null,
        ctx = null,
        gameover = false,
        pause = false,
        score = 0;

    //////////////////////////////////////////////////
    ////////////////////Métodos privados/////////////////
    ////////////////////////////////////////////////////////
    window.requestAnimationFrame = (function(callback) //Función autoejecutable que detecta la compatibilidad del navegador con la animación
        {
            return window.requestAnimationFrame ||
                window.webkitRequestAnimationFrame ||
                window.mozRequestAnimationFrame ||
                window.oRequestAnimationFrame ||
                window.msRequestAnimationFrame ||
                function(callback) {
                    window.setTimeout(callback, 1000 / 60);
                };
        })();

    function loop() //Actualiza los estados y dibuja los elementos durante la partida
    {
        update();
        draw();
    }

    function update() //Actualiza el estado del juego
    {
        window.requestAnimationFrame(update);

    }

    function draw() //Dibuja los elementos del juego en el canvas
    {
        ctx.drawImage(buffer, 0, 0); //Dibujamos el buffer en el contexto
    }

    //////////////////////////////////////////////////
    ////////////////////Métodos públicos/////////////////
    ////////////////////////////////////////////////////////
    function init() {
        var i = 0;
        alert(i);
    }

    return //Devuelve un objeto con todos los métodos públicos
    {
        init: init;
    };
}());

game.init();
Sushil
  • 2,837
  • 4
  • 21
  • 29
  • the problem is on this line `init: init;` - what do you want it to do? Are you calling the `init() ` function? Functions explained: http://www.w3schools.com/js/js_functions.asp Useful links for help with javascript and debugging are here http://stackoverflow.com/tags/javascript/info – Mousey Sep 09 '15 at 00:27
  • The semicolon here is a syntax error: `init: init;`. Use `init: init` – RobG Sep 09 '15 at 00:28
  • 1
    @RobG there is no rule on SO which states I should avoid w3schools or any other source- w3schools has the Try It function which is very handy. – Mousey Sep 09 '15 at 00:36
  • BTW, you can create tutorials with runnable snippets on [*GitHub*](https://github.com/cdnjs/tutorials) – RobG Sep 09 '15 at 06:36

2 Answers2

1

The problem is with your return statement, specifically the semicolon after init as well as the newline after the return keyword.

Change to:

return {
    init: init
};

var game = (function() {
    //////////////////////////////////////////////////
    /////////////////Atributos del juego/////////////////
    ////////////////////////////////////////////////////////
    var canvas = null,
        ctx = null,
        gameover = false,
        pause = false,
        score = 0;
    
    

    //////////////////////////////////////////////////
    ////////////////////Métodos privados/////////////////
    ////////////////////////////////////////////////////////
    window.requestAnimationFrame = (function(callback) //Función autoejecutable que detecta la compatibilidad del navegador con la animación
        {
            return window.requestAnimationFrame ||
                window.webkitRequestAnimationFrame ||
                window.mozRequestAnimationFrame ||
                window.oRequestAnimationFrame ||
                window.msRequestAnimationFrame ||
                function(callback) {
                    window.setTimeout(callback, 1000 / 60);
                };
        })();

    function loop() //Actualiza los estados y dibuja los elementos durante la partida
    {
        update();
        draw();
    }

    function update() //Actualiza el estado del juego
    {
        window.requestAnimationFrame(update);

    }

    function draw() //Dibuja los elementos del juego en el canvas
    {
        ctx.drawImage(buffer, 0, 0); //Dibujamos el buffer en el contexto
    }

    //////////////////////////////////////////////////
    ////////////////////Métodos públicos/////////////////
    ////////////////////////////////////////////////////////
    function init() {
        var i = 0;
        alert(i);
    }

    //Devuelve un objeto con todos los métodos públicos
    return {
        init: init
    };
}());

game.init();

With regard to the newline, see: Why doesn't a Javascript return statement work when the return value is on a new line?

Community
  • 1
  • 1
Drazen Bjelovuk
  • 5,201
  • 5
  • 37
  • 64
  • 1
    I don't see a solution here? – Mousey Sep 09 '15 at 00:28
  • @Mousey He posted a problem with a specific error being thrown in his code. This is the source of that error. – Drazen Bjelovuk Sep 09 '15 at 00:33
  • repeating the entire code isn't helpful, and you have not suggested how to fix the problem - only where the problem is. – Mousey Sep 09 '15 at 00:39
  • I clearly pointed out the problem is with the newline after his `return` keyword. You're quibbling. – Drazen Bjelovuk Sep 09 '15 at 00:43
  • The semicolon is not the problem. it still down – Carlos Sala Samper Sep 09 '15 at 00:47
  • You are aware that only the `init()` function in your snippet works? None of the others do. – Limnic Sep 09 '15 at 00:51
  • @DrazenBjelovuk omg... thank you very much! I thought an enter wasnt important.... is it that only in the return object? – Carlos Sala Samper Sep 09 '15 at 00:55
  • @Limnic He's not shown to be calling any of the other functions outside of their local scope. I've clarified his specific error, this isn't a site for giving tutorials. If he runs into further problems he can ask another question or simply do his own research given the plethora of resources already available on the internet. – Drazen Bjelovuk Sep 09 '15 at 00:55
  • @CarlosSalaSamper Usually. The interpreter infers a newline after a return keyword as a missing semi-colon, so essentially inserts one anyway. See http://stackoverflow.com/questions/8528557/why-doesnt-a-javascript-return-statement-work-when-the-return-value-is-on-a-new – Drazen Bjelovuk Sep 09 '15 at 01:13
0

The real issue was this

   return // comment
   { 
      init: init 
   };

Because of automatic semicolon insertion, the javascript parser interprets this as

  return;

You can read more about this in Justifying Crockford claims, under 'Why should every single statement end with ;?'

var app = document.getElementById('app');
var game = (function() {
    function init() {
        var i = 0;
        app.innerHTML += '<p>game initialized</p>';
    }
    // beware of http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/
    return { init: init }
}());
game.init();
<div id="app"></div>
Community
  • 1
  • 1
widged
  • 2,749
  • 21
  • 25