You need to enable JavaScript to run this app. 如何在JS类constructor中利用同构造函数内变量计算生成属性
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 10:24:00