我有这段代码:
class A {
static b() {
}
}
class B {
static c() {
}
}
我正在尝试将这两个静态类合并为一个:
const combined = { ...A, ...B };
但是,当我期望一个包含所有静态方法组合的对象时,组合的对象会产生一个空对象。
我做错了什么?
最佳答案
您可以使用 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.A.b();
如果您希望能够调用 combined.b()
,您可以执行以下操作。请注意,这种方式在多个类中具有相同名称的方法将发生冲突。例如。如果您同时定义了 A.b
和 B.b
,则 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 B.c, 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.A.b();
console.log(combined.B.c('world', 'universe'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
当您向类 A
或 B
添加新的静态方法时,它们也将自动通过 combined
可用。如果您创建一个新类 C
,您只需调用 addMethodsToCombined(C)
。
关于Javascript es6 将 2 个静态类组合成一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48361655/