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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:06:16