【问题标题】:Make one function accept parameters from the other使一个函数接受另一个函数的参数
【发布时间】:2023-03-22 06:18:01
【问题描述】:

我有这个任务:

编写构造函数来创建代表学生的对象 - 它们将包括名字、姓氏、索引号、带有成绩的表格以及打印名字、姓氏和平均成绩的方法。用它来创建一个代表你自己的对象。

所以根据我的理解,我需要创建两个构造函数:一个应该是一个接受特定学科成绩参数的函数,并计算特定学生的特定成绩集的平均成绩。

我正在尝试了解如何传递这样的内容

function Grade(math, compsc, sc){
    this.math = math;
    this.compcs = compsc;
    this.sc = sc;
}

变成这样的东西(或者让它引用它,或者以某种方式将那些预定义的等级参数值的参数传递给这个函数)

function Student(index, first, last, grade) {
    this.indexNum = index;
    this.firstName = first;
    this.lastName = last;
    this.grade = grade;
    this.gradeAvg = function gradeAvg() {
        let total = 0;
        for (let value in this.grade) {
          total += this.grade[value]
        }
        return total / Object.entries(this.grade).length;
    };
    this.outPrint = function outPrint() {
        console.log("Student number: " + JSON.stringify(this.indexNum) + "\n First name: " + this.firstName + "\n Last name: " + this.lastName + "\n Grades: \n Math:" + this.grade.math + "\n compcs:"+ this.grade.compcs + "\n sc:" + this.grade.sc + "\n average grade:"+ this.gradeAvg())
    }
}

理想情况下,它应该是这样的,但可以正常工作:

function Student(index, first, last, grade) {
    this.indexNum = index;
    this.firstName = first;
    this.lastName = last;
    grade = function(math, copcsc, sc){
        this.math = math;
        this.compsc = compcs;
        this.sc = sc;
    };
    this.gradeAvg = function gradeAvg() {
        let total = 0;
        for (let value in this.grade) {
          total += this.grade[value]
        }
        return total / Object.entries(this.grade).length;
    };
    this.outPrint = function outPrint() {
        console.log("Student number: " + JSON.stringify(this.indexNum) + "\n First name: " + this.firstName + "\n Last name: " + this.lastName + "\n Grades: \n Math:" + this.grade.math + "\n compcs:"+ this.grade.compcs + "\n sc:" + this.grade.sc + "\n average grade:"+ this.gradeAvg())
    }
}

然后初始化

    const me = new Student (345345, 'jora', 'orlovskiy',{math:10, compcs: 10, sc: 5})
console.log(me.outPrint());

和等级

const meGr = new grade(2,2,2)

我知道我的错误可能是语法或理解基本概念的愚蠢错误。也许初始化是错误的,但我尝试了一切以使其以不同的方式工作,但没有任何帮助,不胜感激

【问题讨论】:

    标签: javascript function object methods constructor


    【解决方案1】:

    使用您的原始版本的Student()

    然后在new Student()的参数中调用new Grade()

    const me = new Student (345345, 'jora', 'orlovskiy', new Grade(10, 10, 5));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多