简体   繁体   中英

How can I wrap a class so that its methods are all passed a certain extra parameter by default?

Let's say I have the following class that's been provided by an external library:

class ExampleClass {
    methodA(a, b, c) {}
    methodB(a, b, c) {}
    methodC(a, b, c) {}
}

How can I wrap this class, so that a value to parameter C is always provided, such that I can call the methods as normal, but leave out parameter C?

For example, let's assume parameter C is 20 by default, I can then do this:

new ExampleClass().methodA(12, 14)

And the resulting parameters are:

a=12, b=14, c=20

new ExampleClass().methodB(39, 12)

And the resulting parameters are:

a=39, b=12, c=20

new ExampleClass().methodC(18, 14)

And the resulting parameters are:

a=18, b=14, c=20

I've been doing some reading into ES6 Proxies, looks like apply() could work here, but I can't seem to get the implementation right.

EDIT: Also note that the method names are unpredictable and dynamically generated. I need to generically apply this. I can't extend the class and use super.

Example with a Proxy :

 class ExampleClass { methodA(a, b, c) {console.log('A', a, b, c)} methodB(a, b, c) {console.log('B', a, b, c)} methodC(a, b, c) {console.log('C', a, b, c)} } function ExampleClassWithC(obj, c) { return new Proxy(obj, { get(target, p) { if (typeof target[p] === 'function') return (a, b) => target[p](a, b, c) return target[p] } }) } let c = ExampleClassWithC(new ExampleClass, 'myC') c.methodA(1, 2) c.methodB(3, 4) c.methodC(5, 6)

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