Search code examples
javascriptcraftyjs

Undefined variables in well defined loops


I wonder if you can set me straight on some javascript I'm a little confused with. The code is over here: http://jsfiddle.net/Lbd5k5zh/. The piece of code that escapes me is:

[...]
// Locate this entity at the given position on the grid
  at: function(x, y) {
    if (x === undefined && y === undefined) {
      return { x: this.x/Game.map_grid.tile.width, y: this.y/Game.map_grid.tile.height }
    } else {...}
  }

If I'm in a nested loop for instance:

for(x=0;x<24;x++):
  for(y=0;y<16;y++)

so x,y are clearly well defined and generating cartesian co-ords like thus:

(0,0) (1,0) (2,0)... (23,0)
(0,1) (1,1) (2,1)... (23,1)
(0,2) (1,2) (2,2)       .
.        .              .
.             .         .
.                  .    .
(0,14)(1,14)(2,14)
(0,15)(1,15)(2,15)...(23,15)

How will x or y ever become undefined? Moreover, I don't see where/how

return { x: this.x/Game.map_grid.tile.width === this.x/16

this.x becomes initialised? I realise it's an edge case but struggle to come up with a scenario where it may be used.


Solution

  • The point of checking if the arguments are undefined is do give 2 different behaviors (APIs) to the function.

    If you call obj.at() (no arguments, i.e the body of the function will see the arguments as undefined), this function acts as a getter: it returns current coordinates.

    If you call obj.at(x,y), this function acts more as a setter (sets the current position), from what I have seen. This is the case of the code in your post.

    Whether designing functions API that way is good practice or not is debatable; your confusion is an argument in favor of the no.