Search code examples
javascriptconstructorjavascript-objects

Javascript object


function Person(fname, lname) {
 this.fname = fname,
 this.lname = lname,
 this.getName = function(){
 console.log(`${fname} ${lname}`)
 }
}
var x1 = new Person(“amnah”, “khatun”)
var x2 = new Person(“xyz”, “pqr”)
console.log(x1.getName())

output:

amnah khatun
undefined

I m only calling x1.getName() why both are getting called and o/p coming as undefined for 2nd one. How to fix this. I have tried using protype property but that worked out either.


Solution

  • 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())