0

I have the following code where I am looping over an object and displaying its property values or calling the value if its a function.

 let person = {
  fname: "Joseph",
  lname: "Michuki",
  age: 22,
  profession: "developer",
  address: "10105550-81 Othaya",
  fullname: () => this.fname + " " + this.lname
};

for(i in person){
    if(typeof person[i] === 'function'){
        console.log(person[i]()); // this logs undefined since the value of this defaults to window which has no fname or lname variables
        console.log(person.i); //this results in a type error since i is a string and not a function
        console.log(person[i].call(person)); //this logs undefined undefined since the 'this' passed is ignored
    }else {
        console.log(person[i]);
    }
}

My question is, how do I refer to the 'fullname' function of the person object inside the loop so that it logs the correct value? Thank you.

  • 1
    `person[i]();` is correct. The problem is how you define `username`, not how you call it. Use `function` function syntax or method syntax, not arrow function syntax. Arrow functions inherit `this` from where they're defined, not how they're called like other functions. – T.J. Crowder Jan 06 '18 at 09:33
  • Hello, here is my solution, I think you should return a value in your lamba function (fullname) and call it using person[i].fullname() => which concat fname + lname instead of this.fname and this.lname ;) fullname: function () { return fname + ' ' + lname; } // to set a value => person[i].fullname = fname + ' ' + lname; – andrea06590 Jan 06 '18 at 10:28

0 Answers0