Is there any way to avoid iterating over a method other than doing a `typeof obj[key] !== ‘function’ check inside the for in loop? I would have assumed methods were not enumerable by default.
const obj = Object.create({
b : 2,
c : 3,
init(name, title, age) {
this.name = name;
this.title = title;
this.age = age;
return this;
}
}, {
key1 : { value : 'val1', enumerable : true }
});
const child1 = Object.create(obj).init('Joe', "Boss", 44)
for (const key in child1) {
console.log(`child1 ${key} : ${child1[key]}`) // prints the function name and defintion
const obj = Object.create({
b : 2,
c : 3,
key1: 'val1'
}, {
init: {
value: function(name, title, age) {
this.name = name;
this.title = title;
this.age = age;
return this;
},
enumerable: false
}
});
const child1 = Object.create(obj).init('Joe', "Boss", 44)
for (const key in child1) {
console.log(`child1 ${key} : ${child1[key]}`);
}
Displays:
child1 name : Joe
child1 title : Boss
child1 age : 44
child1 b : 2
child1 c : 3
child1 key1 : val1
You would need to explicitly define the prop init as enumerable: false to achieve not including it as a key.
1 Like
Not really sure if this is what you are asking for?
for (const key in child1) {
if (child1.hasOwnProperty(key)) {
console.log(`child1 ${key} : ${child1[key]}`)
}
}