[英]How can I wrap a class so that its methods are all passed a certain extra parameter by default?
假設我有以下由外部庫提供的 class :
class ExampleClass {
methodA(a, b, c) {}
methodB(a, b, c) {}
methodC(a, b, c) {}
}
如何包裝這個 class,以便始終提供參數 C 的值,以便我可以正常調用方法,但省略參數 C?
例如,假設參數 C 默認為 20,那么我可以這樣做:
new ExampleClass().methodA(12, 14)
結果參數是:
a=12, b=14, c=20
new ExampleClass().methodB(39, 12)
結果參數是:
a=39, b=12, c=20
new ExampleClass().methodC(18, 14)
結果參數是:
a=18, b=14, c=20
我一直在閱讀 ES6 代理,看起來 apply() 可以在這里工作,但我似乎無法正確實現。
編輯:另請注意,方法名稱是不可預測的並且是動態生成的。 我需要一般地應用這個。 我無法擴展 class 並使用超級。
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.