Anonymous Anonymous - 3 years ago 490
Javascript Question

Javascript prototype

Using a constructor function and a prototype, I want the Grade function to output a number grade into a letter grade.

function Grade(name, grade) {
this.name = name;
}

Grade.prototype.grade = function(){
if(grade >= 90){return "A"}
else if (grade <90 && grade >=80){return "B"}
else if(grade <80 && grade >= 70) {return "C"}
else {return "fail"}
};
var sally = new Grade("Sally", 72);
console.log(sally.grade());
console.log(sally.name);

Answer Source

You need to initialize the grade you pass in to the constructor as well as any other properties you want available to the newly created object, not just the name. And change the name of the grade method to getGrade or any other name you'd like to avoid it getting shadowed by the property.

function Grade(name, grade) {
    this.name = name;
    this.grade = grade;
}

Grade.prototype.getGrade = function() {
    if(this.grade >= 90){return "A"}
    else if (this.grade <90 && this.grade >=80){return "B"}
    else if(this.grade <80 && this.grade >= 70) {return "C"}
    else {return "fail"}
}

var sally = new Grade("Sally", 72);
console.log(sally.getGrade());  // C
console.log(sally.name); // Sally
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download