I have an object
of functions
& I need to add a new, single method
called log
(it prints the method
's name) to each function
within the Object
dynamically at runtime.
For instance, let's say this is my dynamic object
of functions
:
let actions = {
theBoringFunction() {
return 'function 1'
},
anotherBoringFunction() {
return 'function 2'
},
theMostBoringFunction() {
return 'function 3'
},
}
I can add a new function
to the methods individually like so:
actions.anotherBoringFunction.log = function () {
return console.log(this.name)
}
actions.anotherBoringFunction.log() // logs anotherBoringFunction
It works like a charm, but I have many functions
within the actions object
& I need to add log()
to all of them.
I have tried looping through the object
& adding the method
like so:
// won't work key is typeof String :(
for (let key in actions) {
key.log = function () {
return console.log(this.name)
}
}
Obviously, it didn't work cause key
is a type of string
so it cannot add a method
to it. How could I accomplish what I'm looking for? I have been trying with proxies, but no luck so far either.
Edit Number 1:
I have added a reproducible, example here.
let actions = {
theBoringFunction() {
return 'function 1'
},
anotherBoringFunction() {
return 'function 2'
},
theMostBoringFunction() {
return 'function 3'
},
}
// won't work key is typeof String :(
/* for (let key in actions) {
key.log = function () {
return console.log(this.name)
}
} */
actions.anotherBoringFunction.log = function () {
return console.log(this.name)
}
actions.anotherBoringFunction.log() // logs anotherBoringFunction