我有點在JavaScript中繼承。比方說,我有一個下面的類:動態從JavaScript中的類的實例繼承
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是允許的。
「裝飾者」,你的意思是Python像裝飾? – Arnial
@Arnial:https://github.com/wycats/javascript-decorators/blob/master/README.md。 –
我的意思是:https://github.com/wycats/javascript-decorators – Ch4rAss