You are actually not returning anything from function console.log(x1.getName())
will log the value returned from function which is undefined
.
You should return the string instead of logging.
function Person(fname, lname) {
this.fname = fname,
this.lname = lname,
this.getName = function(){
return `${fname} ${lname}`
}
}
var x1 = new Person('amnah', 'khatun')
var x2 = new Person('xyz', 'pqr')
console.log(x1.getName())
Another point is that not logging the value of property you are turning the value from closure. It will x1.getName
will always return same even if you change property.
function Person(fname, lname) {
this.fname = fname,
this.lname = lname,
this.getName = function(){
return `${fname} ${lname}`
}
}
var x1 = new Person('amnah', 'khatun')
x1.fname = 'changed';
console.log(x1.getName())
To fix this use this before properties.
this.getName = function(){
return `${this.fname} ${this.lname}`
}
However this is not good to add methods to constructors. In this each and every instance of Person
will have its own function getName
. You should use prototype
function Person(fname, lname) {
this.fname = fname
this.lname = lname
}
Person.prototype.getName = function(){
return `${this.fname} ${this.lname}`;
}
var x1 = new Person('amnah', 'khatun')
var x2 = new Person('xyz', 'pqr')
console.log(x1.getName())