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:
asked Dec 13, 2016 at 21:33
Benua
2691 gold badge3 silver badges20 bronze badges
-
1You aren't actually using a prototype.SLaks– SLaks2016年12月13日 21:34:35 +00:00Commented Dec 13, 2016 at 21:34
2 Answers 2
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();
answered Dec 13, 2016 at 21:36
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Your code never actually calls the function.
Instead, you concatenate the function itself directly into the string.
You want parentheses.
answered Dec 13, 2016 at 21:35
SLaks
891k182 gold badges1.9k silver badges2k bronze badges
Comments
lang-js