如何在JS类constructor中利用同构造函数内变量计算生成属性
JS类构造函数内自动生成实例属性的实现方案
问题需求
定义CreateNewWord类时,希望在构造函数中直接用传入的title参数调用内部方法生成letters属性,实例化对象时无需额外传入letters参数。
原错误代码
class CreateNewWord { constructor(id, title, hold, droppedHere, bg) { this.id = id; this.title = title; // 需要使用该参数生成letters属性 this.hold = hold; this.droppedHere = droppedHere; this.bg = bg; this.letters = getLetter(title); // 期望实现的效果,原写法会报错 } // 错误的类方法定义语法 function getLetter(word) { let letters = []; for (let i = 0; i < word.length; i++) { letters.push({ id: i + 1, title: word[i], hold: false, droppedHere: false, bg: "#a29bfe", }); } return letters; } }
修正方案
- 类内定义成员方法无需加
function关键字,直接以方法名(参数){}格式声明即可 - 构造函数内调用类自身的方法需要通过
this访问,将赋值语句修改为this.letters = this.getLetter(title);
修正后完整代码
class CreateNewWord { constructor(id, title, hold, droppedHere, bg) { this.id = id; this.title = title; this.hold = hold; this.droppedHere = droppedHere; this.bg = bg; this.letters = this.getLetter(title); } getLetter(word) { let letters = []; for (let i = 0; i < word.length; i++) { letters.push({ id: i + 1, title: word[i], hold: false, droppedHere: false, bg: "#a29bfe", }); } return letters; } }
内容的提问来源于stack exchange,提问作者Rostyk
相关产品推荐
相关产品推荐

