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调试,其实很简单:
- 打开浏览器开发者工具(按F12),切换到
Sources面板 - 当代码运行到
debugger语句时会自动暂停 - 此时你可以查看
this的属性:如果构造函数正确执行,this里会有nom和prenom;如果没执行,this就是空的Contact实例,一眼就能看出问题。
修正后再运行debugContact()或者main(),就能正常初始化联系人、调用afficheInfos()返回正确的信息了。
内容的提问来源于stack exchange,提问作者猫IT
相关产品推荐
相关产品推荐

