我需要使用 OOP 方式调用一些方法,例如 this.method() 但我得到了一些错误,请这是我的 BingoCard.js 帮助。
var _ = require('underscore');
// ------------------------------------ ---------
// Constructor
// ---------------------------------------------
function BingoCard() {
if(false === (this instanceof BingoCard)) {
return new BingoCard();
}
this.firstRowSchema = [];
this.secondRowSchema = [];
this.thirdRowSchema = [];
this.firstRow = [];
this.secondRow = [];
this.thirdRow = [];
this.patterns = [
{
"1" : ['x','0','x','0','x','0','x','x','0'],
"2" : ['0','x','0','x','0','x','0','x','x'],
"3" : ['x','0','x','0','x','0','x','0','x']
},
{
"1" : ['x','x','0','x','0','x','0','x','0'],
"2" : ['0','x','x','0','x','0','x','0','x'],
"3" : ['x','0','x','x','0','x','0','x','0']
}
];
this.columns = {
"1": [1,2,3,4,5,6,7,8,9],
"2": [10,11,12,13,14,15,16,17,18,19],
"3": [20,21,22,23,24,25,26,27,28,29],
"4": [30,31,32,33,34,35,36,37,38,39],
"5": [40,41,42,43,44,45,46,47,48,49],
"6": [50,51,52,53,54,55,56,57,58,59],
"7": [60,61,62,63,64,65,66,67,68,69],
"8": [70,71,72,73,74,75,76,77,78,79],
"9": [80,81,82,83,84,85,86,87,88,89,90]
};
// Use Underscore to bind all of our methods
// to the proper context
_.bindAll(this);
}
// ---------------------------------------------
// Methods
// ---------------------------------------------
BingoCard.prototype = {
resetSchemas: function () {
this.firstRowSchema = [];
this.secondRowSchema = [];
this.thirdRowSchema = [];
},
generateRows: function () {
this.cardID = _.random(8888, 999999999); // generate a Card ID.
var pattern = _.shuffle(this.patterns);
this.firstRow = pattern[0][1];
this.secondRow = pattern[0][2];
this.thirdRow = pattern[0][3];
},
createColNumber: function (col,equalNumbers) {
console.log(this.patterns);
var colNumber = this.getColNumber(col);
if(typeof equalNumbers !== 'undefined' && equalNumbers.length > 0){
equalNumbers.forEach(function(val,key){
while(colNumber == val){
colNumber = this.getColNumber(col);
}
});
}
return colNumber;
},
getColNumber: function () {
var items = _.shuffle(this.columns[col]);
return items[0];
},
generateFirstRow: function () {
var col = 0;
this.firstRow.forEach(function(val,key){
col++;
if(val == 'x'){
this.firstRowSchema[key] = this.createColNumber(col);
} else {
this.firstRowSchema[key] = 0;
}
});
return this.firstRowSchema;
}
};
// ---------------------------------------------
// Export
// ---------------------------------------------
module.exports = BingoCard;
我在 app.js 中调用 bingocard 类,这是我的 app.js 内容。
var BingoCard = require('./bingocard');
var bingocard = new BingoCard();
bingocard.generateRows();
console.log(bingocard.generateFirstRow());
从控制台运行“节点应用程序”时,我收到此错误:
TypeError: Object #<Object> has no method 'createColNumber'
at /var/www/bingo/bingocard.js:10:48
但是定义了 createColNumber 方法.. :(?