我有点为 JavaScript 中的继承而苦恼。假设我有以下类(class):
class Parent {
constructor({ name, someOtherStuff } = {}) {
this.name = name;
this.someOtherStuff = someOtherStuff;
}
someMethod() {
// ...
}
}
我想创建一个装饰器,它允许我执行以下操作:
@parent({
name: 'foo',
someOtherStuff: 'bar'
})
class MyClass extends Component {
myMethod() {
// ...
}
}
const instance = new MyClass();
// Those tests must pass
expect(instance.someMethod).toBeFunction();
expect(instance.name).toEqual('foo');
expect(instance.someOtherStuff).toEqual('bar');
expect(instance.myMethod).toBeFunction();
expect(instance instanceof Parent).toBe(true);
expect(instance instanceof MyClass).toBe(true);
有没有办法创建这样的装饰器?我尝试了多种解决方案,但没有一个真正满足所有测试。
const parent = (...args) => (Target) => {
// Target corresponds to MyClass
const parent = new Parent(...args);
// ...
};
lodash 是允许的。
最佳答案
为什么要使用装饰器?你可以只扩展父类
class MyClass extends Parent {
constructor() {
super({name: 'foo', someOtherStuff: 'bar'});
}
}
关于javascript - 从 JavaScript 中的类实例动态继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38746795/