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()
2 Answers
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
Comments
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'
})
()aren't part of the property name. Why would you expect them to appear when you printkey?