1

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.

serakfalcon
  • 3,501
  • 1
  • 22
  • 33
cookie
  • 2,546
  • 7
  • 29
  • 55

1 Answers1

3

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.

Valentin Waeselynck
  • 5,950
  • 26
  • 43
  • Just to pick-up on that point. Assuming I call `obj.at()` (with no arguments) where then are the values for `this.x, this.y` coming from if they're undefined? The loop variables? – cookie Aug 11 '14 at 11:14
  • 1
    when calling `obj.at()`, `this.x` and `this.y` resolve to `obj.x` and `obj.y` in the body of `obj.at`. But you must understand that `x`(the argument) has nothing to do with `this.x` (property of object `this` with name "x"). – Valentin Waeselynck Aug 11 '14 at 11:19
  • Well explained @ Valentin. I just did some logging to the console: `[...] else if (Math.random() < 0.06) { // Place a bush entity at the current tile Crafty.e('Bush').at(x, y); console.log(Crafty.e('Bush').at()); }` Assuming `Math.random()` occurs `n` times then my log shows `Object {x=0, y=0}`, `n` times. Or for each occurrence of `Crafty.e('Bush').at()`. The quotient of `0/16` is zero for all `x & y` resp, moreover it doesn't give me the current co-ords as I progress through the loop? – cookie Aug 11 '14 at 12:02
  • @AndrewCookson Sorry, didn't get your comment question. – Valentin Waeselynck Aug 11 '14 at 12:20
  • OK, no worries. I'll leave that for now. Thanks for your help. – cookie Aug 11 '14 at 12:27