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

如何编写getInfo函数实现调用时输出Student类的学生信息

现有代码问题修正

首先你写的代码里有两个小问题需要先调整:

  • JavaScript 类的构造函数关键字是全小写的constructor,你写的大写Constructor无法正常完成实例初始化
  • 构造函数内部没有给类的实例属性赋值,传入的参数没法绑定到生成的学生对象上

修正后的Student类代码如下:

class Student {
    Name
    Adress
    Phone
    Course 
    constructor(Name, Phone, Adress, Course) {
        this.Name = Name
        this.Phone = Phone
        this.Adress = Adress
        this.Course = Course
    }
}

getInfo函数实现方案

根据你的使用场景可以二选一:

方案1:直接用你声明的四个全局变量传参调用

不需要依赖Student类,直接处理传入的四个参数输出信息:

// 你之前声明的全局变量
var Name= "Stefan"
var Adress= "Strada Campia Islaz numarul 50"
var Phone="+40766334455"
var Course="Curs Javascript"

function getinfo(Name, Adress, Phone,Course) {
    const studentInfo = `学生信息如下:
姓名:${Name}
居住地址:${Adress}
联系电话:${Phone}
所选课程:${Course}`
    // 打印信息的同时支持返回信息字符串给其他逻辑调用
    console.log(studentInfo)
    return studentInfo
}

// 调用测试
getinfo(Name, Adress, Phone, Course)

方案2:配合Student类使用,传入学生实例获取信息

更符合面向对象的写法,复用性更高:

// 先实例化学生对象
const stefan = new Student("Stefan", "+40766334455", "Strada Campia Islaz numarul 50", "Curs Javascript")

function getinfo(student) {
    const studentInfo = `学生信息如下:
姓名:${student.Name}
居住地址:${student.Adress}
联系电话:${student.Phone}
所选课程:${student.Course}`
    console.log(studentInfo)
    return studentInfo
}

// 调用测试
getinfo(stefan)

内容的提问来源于stack exchange,提问作者Piturca Stefan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 14:45:05