I'm still learning about OOP in javascript. While browsing some tutorials I've encountered this code
function Employee () {}
Employee.prototype.firstName = "Abhijit";
Employee.prototype.lastName = "Patel";
Employee.prototype.startDate = new Date();
Employee.prototype.signedNDA = true;
Employee.prototype.fullName = function () {
console.log(this.firstName + " " + this.lastName);
};
var abhijit = new Employee () //
console.log(abhijit.fullName()); // Abhijit Patel & undefined
console.log(abhijit.signedNDA);// true
What I would like to ask is why does abhijit.fullName()
displays undefined?
I'm not asking how to resolve this, I just wanna know why? Thank you.
Execution of console.log(abhijit.fullName())
breaks up into the following:
1) execution of console.log(abhijit.firstName + " " + abhijit.lastName)
, which comes from inner abhijit.fullName()
call, which prints a string and which returns nothing (say undefined
);
2) execution of outer console.log(undefined)
where undefined
is the result of (1).
To avoid such a behaviour you need to change your code a bit:
Employee.prototype.fullName = function () {
return this.firstName + " " + this.lastName;
};
console.log(abhijit.fullName());
or
Employee.prototype.printFullName = function () {
console.log(this.firstName + " " + this.lastName);
};
abhijit.printFullName();
Also, I would recommend not to keep specific data on prototype, but on instance:
function Employee(first, last) {
this.firstName = first;
this.lastName = last;
}
Employee.prototype.fullName = function () {
return this.firstName + " " + this.lastName;
};
var abhijit = new Employee('Abhijit', 'Patel');
console.log(abhijit.fullName());