Home javascript android java php c# ubuntu python c++ c ios TAGS

Javascript object


Date : 2019-05-17 10:52:47 , By : Amnah khatun
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.

TAGS : javascript
Answers :
By : Maheer Ali

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

- Technology - Yellow pages
» java
» php
» c#
» ubuntu
» python
» c++
» c
» ios
» jquery
» html
» sql
» r
» mysql
» linux
» access
» iphone
» css
» excel
» vb.net
» .net
» ruby
Privacy Policy - Copyrights Notice - Terms - Contact Us 2019 © tinytut
Licensed under cc by-sa 3.0 with attribution required.