2

I have three methods in an object.

2 of them work properly, when third is printed - it prints out the code itself, not function. Here is the code and how it looks in console:

function Students(name, lastname, grades){
    this.name = name;
    this.lastname = lastname;
    this.grades = grades;
    this.addGrade = function(a){
        this.grades.push(a);
    }
    this.printData = function(){
        console.log("Name: " + this.name);
        console.log("Grades: " + this.grades);
        console.log("Average: " + this.gradeAvg);
    }
    this.gradeAvg = function(){
        console.log("blabla");
    }
}

var StudentasA = new Students("Petras", "Petrauskas", [8, 9, 9, 8, 7]);
var StudentasB = new Students("Jurgis", "Jurgauskas", [6, 7, 5, 4, 9]);
StudentasA.printData();
StudentasA.addGrade(28);
StudentasA.printData();

console:

console view

1
  • 1
    You aren't actually using a prototype. Commented Dec 13, 2016 at 21:34

2 Answers 2

1

You need to call the function

this.gradeAvg()
//           ^^

function Students(name, lastname, grades){
    this.name = name;
    this.lastname = lastname;
    this.grades = grades;
    this.addGrade = function(a){
        this.grades.push(a);
    }
    this.printData = function(){
        console.log("Name: " + this.name);
        console.log("Grades: " + this.grades);
        console.log("Average: " + this.gradeAvg());
        //                                     ^^
    }
    this.gradeAvg = function(){
        return this.grades.reduce(function (a, b) { return a + b; }) / this.grades.length;
    }
}

var StudentasA = new Students("Petras", "Petrauskas", [8, 9, 9, 8, 7]);
var StudentasB = new Students("Jurgis", "Jurgauskas", [6, 7, 5, 4, 9]);
StudentasA.printData();
StudentasA.addGrade(28);
StudentasA.printData();

Sign up to request clarification or add additional context in comments.

Comments

1

Your code never actually calls the function.

Instead, you concatenate the function itself directly into the string.

You want parentheses.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.