0

I'm following a tutorial on how to make a javascript game, but i'm stuck on the return part. Why are is there { }, and what is the init: init for? Any help would be appreciated. Thanks.

var JS_SNAKE = {};

JS_SNAKE.game = (function () {
  var ctx;
  var xPosition = 0;
  var yPosition = 0;
  var frameLength = 500; //new frame every 0.5 seconds

  function init() {
    $('body').append('<canvas id="jsSnake">');
    var $canvas = $('#jsSnake');
    $canvas.attr('width', 100);
    $canvas.attr('height', 100);
    var canvas = $canvas[0];
    ctx = canvas.getContext('2d');
    gameLoop();
  }

  function gameLoop() {
    xPosition += 2;
    yPosition += 4;
    ctx.clearRect(0, 0, 100, 100); //clear the canvas
    ctx.fillStyle = '#fe57a1';
    ctx.fillRect(xPosition, yPosition, 30, 50); //a moving rect
    setTimeout(gameLoop, frameLength); //do it all again
  }

  return {
    init: init
  };
})();


$(document).ready(function () {
  JS_SNAKE.game.init();
});
1
  • How are you stuck? What are you expecting to be returned, and what is occurring (or not occurring) instead? Commented Aug 21, 2011 at 5:20

2 Answers 2

1

The {} is an object literal in JavaScript. The statement

return {
    init: init
}

returns an object with one property. That property's key is init and value is whatever value the variable named init has (in this case, a function).


In case that syntax is confusing, this is equivalent and might be clearer:

JS_SNAKE.game = (function () {
    // snip...

    function performInitialization() {
        // snip...
    }

    // snip ...

    return {
        init: performInitialization
    };
})();
Sign up to request clarification or add additional context in comments.

2 Comments

I mean why can't you just do return init() what's the point of using the braces? I'm confused by the syntax.
return init() returns whatever value is returned by invoking the init function. This is completely different from returning an object which contains an invocable function.
0

That is something that is called a module pattern - where you enclose your "class" (or represent it, if you will) with an anonymous function.

The function returns the JS object that can be used to access "class" methods and variables, but only those that are exposed (public) - such as init.

{} is object literal - it is used here to declare an empty JS_SNAKE object - which will serve as a namespace for the following "class" declaration.

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.