Reputation: 47
I'm getting the values undefined even though it's populated. I think I've already populated it but feels like something is going wrong with the object's instance. That'd be great if someone can explain that where I'm going wrong.
function Student(fn, sn, a, d)
{
this.firstName = fn;
this.lastName = sn;
this.age = a;
this.degree = d;
this.displayStudent = displayStudent;
}
function displayStudent()
{
console.log(this.fn);
console.log(this.sn);
console.log(this.a);
console.log(this.d);
}
var studentObj = new Student("d", "r", 20,
"bachelors of science");
studentObj.displayStudent();
Upvotes: 2
Views: 82
Reputation: 915
I think it's just a typo, your code should be like this:
function Student(fn, sn, a, d)
{
this.firstName = fn;
this.lastName = sn;
this.age = a;
this.degree = d;
this.displayStudent = displayStudent;
}
function displayStudent()
{
console.log(this.firstName);
console.log(this.lastName);
console.log(this.age);
console.log(this.degree);
}
var studentObj = new Student("d", "r", 20,
"bachelors of science");
studentObj.displayStudent();
In your code you tried to print Student's "constructor" attributes instead of Student's "object" parameters you set.
Upvotes: 1
Reputation: 86
You are trying to display the Student constructor parameters instead of displaying the Student properties, a method declared outside the constructor does not have access to the constructor´s parameters. To display the Student properties with the displayStudents() method do this.
function Student(fn, sn, a, d)
{
this.firstName = fn;
this.lastName = sn;
this.age = a;
this.degree = d;
this.displayStudent = displayStudent;
}
function displayStudent()
{
console.log(this.firstName);
console.log(this.lastName);
console.log(this.age);
console.log(this.degree);
}
var studentObj = new Student("d", "r", 20,
"bachelors of science");
studentObj.displayStudent();
Also when you declare methods outside the object constructor you should use the prototype property like this.
function Student(fn, sn, a, d)
{
this.firstName = fn;
this.lastName = sn;
this.age = a;
this.degree = d;
}
Student.prototype.displayStudent = function()
{
console.log(this.firstName);
console.log(this.lastName);
console.log(this.age);
console.log(this.degree);
}
var studentObj = new Student("d", "r", 20,
"bachelors of science");
studentObj.displayStudent();
Upvotes: 1