我正在構建一個國際象棋應用程序,並且遇到了有關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)。 –