1

我有像棋盘这样的二维对象数组。

您可以通过data.field(x,y);(对象存储在二维对象数组中)获取对象

我希望每个字段都有功能:top, bottom, left,right将返回邻居字段。

例如data.field(3,3).top().left().bottom().name将返回字段 (4,3) 的名称。

但是:我必须为每个对象声明这些函数吗?我的意思是,例如在 8x8 字段上,这将是同一函数的 64 个实例:

data.field(0,0).top = function(){...}
data.field(0,1).top = function(){...}
...

Ofc 我可以很容易地在循环中声明它们,但这纯粹是浪费内存,我确信这不是这样做的方法。是否可以仅在 field(x,y) 函数返回的每个对象中声明此函数一次可用?

4

2 回答 2

1

是否可以仅在 field(x,y) 函数返回的每个对象中声明此函数一次?

绝对地:

function top() {
    // ...do your thing, using `this`
}

data.field(0,0).top = top;

当作为从对象中top检索它的表达式的一部分被调用时,在对 的调用中将是对象。同样对于等。field(0,0)topthisfield(0,0)field(0,1)

更多(在我的博客上):

现在,假设无论出于何种原因,您已经拥有了field(0,0)和这样的对象(也许它们是由您无法控制的代码创建的)。如果您控制代码,则可以通过原型链执行此操作:

function Field() {
}
Field.prototype.top = function() {
    // ...do your top thing, using `this`
};

...以及在创建字段时:

yourField = new Field();

所以这取决于你data.fields(0,0)是什么以及你从哪里得到它。

于 2013-03-04T17:25:56.523 回答
0

如果你想节省内存,你应该看看原型。它们就像面向对象语言中的类,因此有机会进行内存优化。

var Field = function() {}; // this is your constructor
Field.prototype.top = function () { /* .. */
    return this; // return the field so you can do chaining: field.top().left();
};
Field.prototype.left = function () { /* .. */
    return this;
};
/* .. */
var field = new Field();
data.set(0, 0, field);
data.field(0, 0).top().left();
于 2013-03-04T17:28:41.167 回答