简体   繁体   中英

Lodash or Javascript decorator for all functions in object

For below object

const ourObject = {
    func1: (arg1, arg2, arg3) => arg3
    func2: (arg1) => void
};

ourFunction(ourObject);

ourObject.func1(1,2,3);

after above I would like to log arguments and return output of func1, so I believe need to iterate thru all fields and then use something like below

console.log(argmuments)
return func.apply(arguments)

does lodash already have solution for it?

So loop over the keys, make a copy, define a new method, reference the arguments, and call the original method.

 const ourObject = { func1: (arg1, arg2, arg3) => arg3, func2: (arg1) => 'bar' } // Loop over the keys of the object Object.keys(ourObject).forEach((key) => { // copy the original method const org = ourObject[key] // create the new method ourObject[key] = function(...args) { // log the arguments console.log(key, args) // call the original return org.apply(this, args) } }) console.log(ourObject.func1(1, 2, 3)) console.log(ourObject.func2('foo'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM