我正在构建一个国际象棋应用程序,并且遇到了有关 JavaScript 中对象定义和实例化之间差异的问题。例如,我想通过 Matrix
模型将我的 Board
模型(和 View )与其表示(嵌套数组)分开:
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 风格的方式是什么?
最佳答案
But the problem is that Board does not have access to Matrix's methods at instantiation, because that relationship is still being defined.
没有。当您使用new
operator时在 Board
上,首先将定义关系(“原型(prototype)链”),然后在新实例上调用 Board
构造函数,它可以在其中调用在实例上使用 Matrix
函数或添加实例属性,例如 .state
。您可以使用原型(prototype)继承的 set
方法,不会出现任何问题。
在 JavaScript 中,继承是在运行时设置的。您可以声明函数体(使用其中的继承方法),然后设置原型(prototype),然后实例化对象。
Board.prototype = Matrix.prototype;
Don't do that 。您需要 Board.prototype = Object.create(Matrix.prototype)
。
关于javascript - 如何在 JavaScript 中处理对象定义与实例化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21684863/