我正在构建一个国际象棋应用程序,并且遇到了有关JavaScript中对象定义和实例化之间差异的问题。例如,我想我Board
模型(以及视图)与它的表示(嵌套数组)通过Matrix
模型分开:如何在JavaScript中处理对象定义与实例化?
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的功能的相关子集需要填充shim)。 –