【发布时间】:2014-02-10 18:13:43
【问题描述】:
我正在构建一个国际象棋应用程序,并且遇到了一个关于 JavaScript 中对象定义和实例化之间差异的问题。例如,我想通过Matrix 模型将我的Board 模型(和视图)与其表示(嵌套数组)分开:
var Matrix = function(n, m) {
// builds an n*m nested array
// e.g. a 2x3 array would look like this:
// [[0, 0], [0, 0], [0, 0]]
};
// A setter, which takes a `Point` object and correctly updates the nested array
Matrix.prototype.set = function(pt, obj) {
this.state[pt.y][pt.x] = obj;
};
// A custom `each` method that iterates over the nested array
Matrix.prototype.each = function(fn) {
// executes `fn` against every (x,y) in the nested array
};
// etc.
然后Board 看起来像这样:
var Board = function(n, m) {
Matrix.call(this, n, m);
// now use `Matrix`'s `set` method to place pieces on the board.
};
Board.prototype = Matrix.prototype;
// etc.
我的问题实际上在于Board 的定义。当我实例化一个新的Board 对象时,我希望它继承Matrix,然后使用Matrix 的方法在板上设置棋子。但问题是Board 在实例化时无法访问Matrix 的方法,因为这种关系仍在定义中。
试图解决这个问题已经澄清了this question 的答案。似乎问题在于Board 不是Matrix 的真正子类。在代码实际执行之前,不会设置这种关系。处理这种关系的 JavaScript 式方式是什么?
【问题讨论】:
-
Board.prototype = Matrix.prototype;是个坏主意。你想要Board.prototype = Object.create(Matrix.prototype);(如果需要,可以为Object.create的相关功能子集使用垫片)。
标签: javascript inheritance prototype subclass