JavaScript类中name()方法无返回值,运行后无输出的问题求助
JavaScript类方法调用与属性访问问题解决
你的代码存在两个问题导致没有输出预期内容:
- 类的
name()方法中,访问实例属性firstName和lastName时未使用this关键字,无法正确获取实例的属性值 - 没有调用
student1的name()方法并执行打印操作
修正后的代码如下:
class Student { constructor(firstName, lastName, age){ this.firstName = firstName this.lastName = lastName this.age = age } name(){ return `The student's name is ${this.firstName} ${this.lastName}` } } const student1 = new Student('John', 'Carter', '26') // 调用方法并打印结果 console.log(student1.name())
执行修正后的代码,命令行将输出:The student's name is John Carter
内容的提问来源于stack exchange,提问作者NinjaTS
相关产品推荐
相关产品推荐

