Reputation: 269
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:
Upvotes: 2
Views: 66
Reputation: 386550
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();
Upvotes: 1
Reputation: 887275
Your code never actually calls the function.
Instead, you concatenate the function itself directly into the string.
You want parentheses.
Upvotes: 1