面向对象的OOJS

时间:2015-12-16 11:24:21

标签: javascript-objects

此代码用于累加标记,计算平均值并确定学生是否通过。但是,它能否是一种正确的面向对象技术,能否以更好的方式完成?

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);

1 个答案:

答案 0 :(得分:0)

查看Introduction to Object-Oriented 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.