2015-12-16 44 views
1

該代碼用於合計標記,計算平均值並確定學生是否合格/不合格。但是,它可以是一個正確的面向對象技術,它是否可以以更好的方式完成?面向對象OOJS

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

回答

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.