Execute function / method of object
Is there a way to make something like this work in JS:
function iterateObject(obj, f) {
for (let prop in obj) {
if (obj.hasOwnProperty(prop)) f(prop);
}
}
And then apply it to the object:
let x = {a : function() {
// do smth
}};
iterateObject(x, (prop) => {
prop.a();
}
I get the error that prop.a () is not a function, but if I call xa () there is no problem. Not very important, but I'm just surprised and can't find the answer.
source to share
Your call contains a string iterateObject
inside the anonymous function . Also, is your original object.prop
"a"
x
To access a property by name ( prop
) for an object ( x
) you will need to do x[prop]
. To call this function, you must write x[prop]()
inside your anonymous function.
source to share
function iterateObject(obj, f) {
for (let prop in obj) {
if (obj.hasOwnProperty(prop)) {
f(obj[prop]);
// You were earlier just passing the key 'a' as a string to the function.
// Hence it was giving you an error
// You need to pass the function i.e obj[prop]
}
}
}
let x = {
a: function() {
console.log('hello');
}
};
iterateObject(x, (prop) => {
// You will get the function as prop
// To execute it you need to directly call it using prop()
prop();
});
source to share