3

let person = {
  firstName: "Rella",
  lastName: "binson",
  age: 18,
  getFullName: function() {
    return this.firstName + ' ' + this.lastName;
  }
};

for (let key in person) {
  if (person.hasOwnProperty(key)) {
    console.log(key + ' ' + person[key])
  }
}
// it doesn't print 'getFullName()

1
  • "it doesn't print 'getFullName()" — Well, no, the () aren't part of the property name. Why would you expect them to appear when you print key? Commented Aug 7, 2020 at 8:59

2 Answers 2

4

Consider using getter property:

let person = {
  firstName: "Rella",
  lastName: "binson",
  age: 18,
  get getFullName() {
    return this.firstName + ' ' + this.lastName;
  }
};

for (let key in person) {
  if (person.hasOwnProperty(key)) {
    console.log(key + ' ' + person[key])
  }
}

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get

Sign up to request clarification or add additional context in comments.

Comments

0

Here is another way to do it with modern Object.keys() method and collecting them into array

let person = {
  firstName: "Rella",
  lastName: "binson",
  age: 18,
  getFullName: function() {
    return this.firstName + ' ' + this.lastName;
  }
}

const objectMethods = Object.keys(person).filter(item => {
  person.hasOwnProperty(item) &&
  typeof person[item] === 'function'
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.