Jump to content

Why does this (boilerplate) code work


ashes999
 Share

Recommended Posts

Hi,

 

Caveat: I'm new to Phaser, new to CoffeeScript, and fairly new (< 6 months) to Javascript. I've written a small-ish game in JS + CraftyJS in the past.

 

I'm trying to convert the "hello world" Phaser app into its equivalent in CoffeeScript. Here's what I have working:

class State  constructor: () ->    preload: () ->        game.load.image('logo', 'phaser.png')  create: () ->      logo = game.add.sprite(game.world.centerX, game.world.centerY, 'logo')      logo.anchor.setTo(0.5, 0.5)window.onload = () ->    @game = new Phaser.Game(800, 600, Phaser.AUTO, '', new State)

I've looked at the equivalent generated JS, but I can't quite figure out why this works; specifically, @game = new Phaser.Game(...) confuses me. TLDR: why do I need to assign the value to @game and not just game?

 

Observations:

 

  • window.game takes the value of the game variable
  • The State class has no references to game, or window, that I can see
  • Changing @game to game breaks the game.

 

Can anyone explain this? It doesn't seem like it has to do with closures, or global variables, or anything else I can think of. Why does this work?

Link to comment
Share on other sites

Question updated. It's not the game state, but the assignment to "game" vs. "@game".

 

I looked at the generated JS (obviously?) and some other stuff (see initial thoughts) -- I think it has something to do with CoffeeScript putting everything in an anonymous lambda (and thus limiting scope), but I can't quite tell what the difference is and what @game belongs to.

Link to comment
Share on other sites

Question updated. It's not the game state, but the assignment to "game" vs. "@game".

 

I looked at the generated JS (obviously?) and some other stuff (see initial thoughts) -- I think it has something to do with CoffeeScript putting everything in an anonymous lambda (and thus limiting scope), but I can't quite tell what the difference is and what @game belongs to.

Caveat: Well I don't know CoffeeScript at all, and got nowhere with Phaser... but I think you just answered your own question.

Surely if you store the game object on a non-static variable that is local to a function and don't return it or anything that references it, then you can expect it to be disposed of when that function returns (or at least not long after)

P.S. after writing the above I spend about 10 seconds to google "coffeescript at symbol", it seems it somewhat equivalent to "this" in javascript at least in regard to class members.

Link to comment
Share on other sites

  • 2 weeks later...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...