开发者

javascript game: why return init: init?

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;
    yPositi开发者_运维百科on += 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();
});


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
    };
})();


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜