首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >面向对象OOJS

面向对象OOJS
EN

Stack Overflow用户
提问于 2015-12-16 19:24:21
回答 1查看 34关注 0票数 1

此代码用于将分数相加,计算平均值,并确定学生是否通过/不及格。但是,它是一种正确的面向对象技术吗?它是否可以用一种更好的方式来完成?

代码语言:javascript
复制
function Student(marks1, marks2, marks3, marks4, marks5, marks6) {
    // To find the sum total of the marks obtained  
    var sum = 0;
    for (var i = 0; i < arguments.length; i++) {
        sum += arguments[i];
    }
    alert(" Total Marks is " + sum);
    console.log(" Total Marks is " + sum);

    // To find the average of the marks
    var average = sum / 6;
    alert(" Average Marks is " + average);
    console.log(" Average Marks is " + average);

    // To check if the student has passed/failed
    if (average > 60) {
        alert("Student has passed the exam");
        console.log("Student has passed the exam");
    } else {
        alert("Student has failed the exam");
        console.log("Student has failed the exam");
    }   
}

var myStudent = new Student(58, 64, 78, 65, 66, 58);
EN

回答 1

Stack Overflow用户

发布于 2015-12-16 20:08:54

看看Introduction to Object-Oriented JavaScript,看看如何使用面向对象的方法编写JavaScript代码。

注意:我会将标记作为数组传递,而不是参数列表。如果需要,您可以更改构造函数以接受对象,这样您就可以传入数量可变的参数。

代码语言:javascript
复制
function Student(args) {
  this.name = args.name || 'Unknown';
  this.marks = args.marks || [];
}
Student.prototype.constructor = Student;
Student.prototype.calcSum = function() {
  return this.marks.reduce(function(sum, mark) {
    return sum + mark;
  }, 0);
}
Student.prototype.calcAvg = function() {
  return this.calcSum() / this.marks.length;
}
Student.prototype.didPass = function() {
  var type = this.calcAvg() > 60 ? 'passed' : 'failed';
  return this.name + " has " + type + " the exam.";
}
Student.prototype.toString = function() {
  return 'Student { name : "' + this.name + '", marks : [' + this.marks.join(', ') + '] }';
}

// Convienience function to print to the DOM.
function print() { document.body.innerHTML += '<p>' + [].join.call(arguments, ' ') + '</p>'; }

// Create a new student.
var jose = new Student({
  name : 'Jose',
  marks : [58, 64, 78, 65, 66, 58]
});
 
print("Total Marks:", jose.calcSum());   // Find the sum total of the marks obtained.
print("Average Marks:", jose.calcAvg()); // Find the average of the marks.
print(jose.didPass());                   // Check if the student has passed/failed.
print(jose);                             // Implicitly call the toString() method.

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34310761

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档