You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript类属性返回undefined:联系人管理脚本故障求助

问题排查:Contact类构造函数拼写错误导致实例属性未初始化、afficheInfos()返回undefined

我一眼就发现了核心问题——你的Contact类里构造函数的拼写出错了!把constructor写成了contructor(少了一个字母c),这直接导致构造函数完全没有被执行:

  • 实例化Contact时,this.nom和this.prenom根本不会被赋值
  • 构造函数内的console.log和debugger自然也不会触发
  • 调用afficheInfos()时,this.nom和this.prenom都是undefined,所以方法返回的字符串里对应位置就是undefined

修正后的核心代码

只需要把构造函数的拼写改对即可:

class Contact {
  // 修正拼写:constructor(正确写法)
  constructor(nom, prenom) {
    this.nom = nom;
    this.prenom = prenom;
    debugger;
    console.log(this);
    // console.log("Nouveau contact ajouté: "+this.toString());
  }
  afficheInfos() {
    return `Nom: ${this.nom}, Prénom: ${this.prenom}`;
  }
}

关于debugger的小提示

你提到不会用debugger调试,其实很简单:

  1. 打开浏览器开发者工具(按F12),切换到Sources面板
  2. 当代码运行到debugger语句时会自动暂停
  3. 此时你可以查看this的属性:如果构造函数正确执行,this里会有nom和prenom;如果没执行,this就是空的Contact实例,一眼就能看出问题。

修正后再运行debugContact()或者main(),就能正常初始化联系人、调用afficheInfos()返回正确的信息了。

内容的提问来源于stack exchange,提问作者猫IT

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:43:20