[英]Javascript es6 combine 2 static classes into an object
我有此代碼:
class A {
static b() {
}
}
class B {
static c() {
}
}
我試圖將這兩個靜態類合並為一個:
const combined = { ...A, ...B };
但是,合並的對象導致一個空對象,而我期望一個包含所有合並的靜態方法的對象。
我究竟做錯了什么 ?
您可以在新對象上設置方法
const combined = {A:A.b, B:B.c}
您可以使用Object.getOwnPropertyNames
獲得類的靜態方法的數組:
class A { static staticMethod() {} nonStaticMethod() {} } console.log(Object.getOwnPropertyNames(A));
有一些我們不感興趣的屬性,即prototype
, length
和name
。 我們可以手動過濾掉它們,例如:
class A { static staticMethod() {} nonStaticMethod() {} } console.log( Object.getOwnPropertyNames(A) .filter(prop => prop !=='prototype' && prop !== 'length' && prop !== 'name') );
好! 現在,我們可以創建combined
對象並向其添加A
的過濾方法:
class A { static b() { console.log('called A.b'); } } const classAMethods = Object.getOwnPropertyNames(A) .filter(prop => prop !== 'prototype' && prop !== 'length' && prop !== 'name'); const combined = {}; combined.A = {}; classAMethods.forEach(method => { combined.A[method] = () => A[method](); }); console.log(combined); combined.Ab();
如果您希望能夠調用combined.b()
,則可以執行以下操作。 請注意,以這種方式,多個類中具有相同名稱的方法將發生沖突。 例如,如果您同時定義了Ab
和Bb
,則combined
只能容納其中之一。
class A { static b() { console.log('called A.b'); } } const classAMethods = Object.getOwnPropertyNames(A) .filter(prop => prop !== 'prototype' && prop !== 'length' && prop !== 'name'); const combined = {}; classAMethods.forEach(method => { combined[method] = () => A[method](); }); console.log(combined); combined.b();
綜上所述,我們有以下幾點。 請注意,在調用類方法時,我使用...args
添加了對傳遞參數的支持。
class A { static b() { console.log('called A.b'); } } class B { static c(name1, name2) { console.log('called Bc, hello', name1, 'and', name2); return 'returned by B.c'; } } const getMethods = (cls) => Object.getOwnPropertyNames(cls) .filter(prop => prop !== 'prototype' && prop !== 'length' && prop !== 'name'); const combined = {}; const addMethodsToCombined = (cls) => { combined[cls.name] = {}; getMethods(cls).forEach(method => { combined[cls.name][method] = (...args) => cls[method](...args); }); }; addMethodsToCombined(A); addMethodsToCombined(B); console.log(combined); combined.Ab(); console.log(combined.Bc('world', 'universe'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
當您將新的靜態方法添加到類A
或B
,它們也將自動通過combined
。 如果創建新的類C
,則只需調用addMethodsToCombined(C)
。
您可以從A擴展B,然后從B擴展另一個類。
如果您使用的是靜態類,最好只使用對象文字
class A { static b() { console.log('called A.b') } } class B extends A { static c() { console.log('called B.c') } } class Combined extends B {} Combined.b() Combined.c()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.