1

我想知道你是否可以让我直接使用一些我有点困惑的javascript。代码在这里:http: //jsfiddle.net/Lbd5k5zh/。逃脱我的代码是:

[...]
// 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 {...}
  }

例如,如果我处于嵌套循环中:

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

所以x,y明确定义并生成笛卡尔坐标,如下所示:

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

将如何xy曾经变得不确定?此外,我不知道在哪里/如何

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

this.x初始化?我意识到这是一个边缘案例,但很难想出一个可以使用它的场景。

4

1 回答 1

3

检查参数是否未定义的重点是为函数提供 2 种不同的行为 (API)。

如果您调用obj.at()(无参数,即函数体将参数视为undefined),则此函数充当 getter:它返回当前坐标。

如果你调用obj.at(x,y),这个函数更像是一个设置器(设置当前位置),从我所看到的。这是您帖子中的代码的情况。

以这种方式设计函数 API 是否是好的做法值得商榷;您的困惑是支持否的论据。

于 2014-08-11T10:34:49.323 回答