无法访问类内函数以打印数组结果,求基于OOP的解决方案
问题描述
我尝试将数组结果打印到控制台,但无法访问类内部的函数。希望把下面的非OOP风格JavaScript代码重构为符合面向对象(OOP)原则的代码,附上了我尝试但卡住的代码:
期望效果的代码
let arrya = []; let arryb = []; for (let i = 0; i <= 9; i++) { function crad_a(max) { a = Math.floor(Math.random() * max); return a; } // console.log(crad_a(10)); function crad_b(max) { b = Math.floor(Math.random() * max); return b; } // console.log(crad_b(10)); i++; arrya.push(crad_a(10)); arryb.push(crad_b(10)); } console.log(arrya); console.log(arryb); for (let j = 0; j <= arrya.length; j++) { if (arrya[j] != arryb[j]) { if (arrya[j] > arryb[j]) { console.log("a" + " " + "win" + " " + " the game"); } else { console.log("b" + " " + "win" + " " + "the game"); } } }
我尝试但卡住的代码
class card_number_one { constructor() { this.card_one = []; this.card_tow = []; } crad_a(max) { for (let d = 0; d <= 9; d++) { a = Math.floor(Math.random() * max); return a; } d++; this.card_one.push(crad_a(10)); } crad_b(max) { for (let i = 0; i <= 9; i++) { b = Math.floor(Math.random() * max); return b; } i++; this.card_tow.push(crad_b(10)); } } console.log(this.card_one); /// Not working for me
重构方案及问题说明
问题根源
- 直接打印
this.card_one时,this指向全局对象(浏览器环境为window),并非类的实例,因此无法访问实例属性。 - 类内的
crad_a/crad_b逻辑存在错误:循环内部第一行就执行return,只会生成一个随机数就终止循环;d++/i++写在循环外部永远不会执行;调用自身方法时未加this,属于全局调用而非实例调用。
重构后的OOP代码
class Game { constructor() { this.cardA = []; this.cardB = []; this.generateCards(); // 实例化时自动生成卡牌数组 } // 生成单个随机数的工具方法 getRandomNum(max) { return Math.floor(Math.random() * max); } // 生成两组卡牌数组 generateCards() { // 保留原代码的i++逻辑,实际生成5个元素(若需10个可删除i++) for (let i = 0; i <= 9; i++) { this.cardA.push(this.getRandomNum(10)); this.cardB.push(this.getRandomNum(10)); i++; } } // 比较卡牌并输出胜负 compareCards() { for (let j = 0; j < this.cardA.length; j++) { // 避免数组越界(原代码j<=length会导致最后一次取undefined) if (!this.cardA[j] || !this.cardB[j]) break; if (this.cardA[j] !== this.cardB[j]) { const winner = this.cardA[j] > this.cardB[j] ? 'a' : 'b'; console.log(`${winner} win the game`); } } } // 打印两组卡牌 printCards() { console.log('卡牌A:', this.cardA); console.log('卡牌B:', this.cardB); } } // 创建游戏实例并执行操作 const game = new Game(); game.printCards(); game.compareCards();
核心改进
- 类和属性命名更语义化,修正原代码拼写错误(如
card_tow改为cardB) - 提取通用的随机数生成方法,减少代码冗余
- 实例化时自动生成卡牌,无需手动触发
- 将打印、比较逻辑封装为独立方法,符合OOP单一职责原则
- 修复原代码循环越界、逻辑跳转错误的问题
- 通过实例化类访问内部属性和方法,解决
this指向错误问题
内容的提问来源于stack exchange,提问作者omrihazan
相关产品推荐
相关产品推荐

