[英]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 :
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?如何包装这个 class,以便始终提供参数 C 的值,以便我可以正常调用方法,但省略参数 C?
For example, let's assume parameter C is 20 by default, I can then do this:例如,假设参数 C 默认为 20,那么我可以这样做:
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.我一直在阅读 ES6 代理,看起来 apply() 可以在这里工作,但我似乎无法正确实现。
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.
我无法扩展 class 并使用超级。
Example with a Proxy
: 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.