【发布时间】:2019-04-26 03:34:57
【问题描述】:
理想情况下,我想做如下的事情:
class Chess = {
constructor() {
this.board = ...;
...
};
class Square = {
constructor(row, col) {
this.row = row;
this.col = col;
};
};
我的主要动机是分开定义 Chess 和 Square 类,例如:(这里指的是 Chess 类)
this.empty(square)
可以缩短为
square.empty()
更易读,更简洁。
不幸的是,我不能只做一个
Square.empty()
方法,因为结果取决于国际象棋类中的信息和
square.empty(chess)
没有真正的改进。
我有一个 Square 类的原因是这样的
square.up()
似乎比类似的东西好得多
[row, col + 1]
您对我将如何完成上述任务有什么建议吗?以某种方式在类中编写类或完全是其他方式?
编辑:
按照 likle 和 alex 的建议,我做了以下事情:
我在类 Square 中添加了一个上下文属性
class Square = {
constructor(context, row, col) {
this.context = context;
this.row = row;
this.col = col;
};
};
然后将 Chess.prototype 中的一些方法重新定义为 Square.protoype。例如:
// before
Chess.prototype.empty = function (square) {
return this.piece(square) === 0;
};
// after
Square.prototype.empty = function () {
return this.piece() === 0;
};
这意味着每次创建 Square 对象时,我都需要添加上下文。例如:
new Square(3, 4); // before
new Square(this, 3, 4); // after
new Square(this.context, 3, 4); // sometimes like this
为了使代码更具可读性,我创建了以下方法:
Chess.prototype.createSquare = function (row, col) {
return new Square(this, row, col);
};
所以有时可以创建一个 Square 对象
this.createSquare(3, 4);
【问题讨论】:
-
您可以将定义分开,只让
Chess实例化Square的实例。
标签: javascript class oop nested