2016-08-03 2 views
1

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); 

    // ... 
}; 

로다 시가 허용됩니다.

+0

"데코레이터"란 데코레이터 같은 파이썬을 의미합니까? – Arnial

+0

@Arnial : https://github.com/wycats/javascript-decorators/blob/master/README.md. –

+0

뜻은 다음과 같습니다. https://github.com/wycats/javascript-decorators – Ch4rAss

답변

3

왜 장식을 사용합니까? 부모 클래스를 확장 할 수 있습니다.

+0

그는 언어의 새로운 기능을 탐색하고 있으며 특정 방법으로 사용할 수 있는지 알고 싶지만 어려움을 겪고 있습니다. 그는 전통적인 방식으로하는 방법을 묻지 않습니다. –

+0

데코레이터가 필요합니다. 왜냐하면 내가 만든 라이브러리의 기능이라고 생각하기 때문입니다. 또한 이미 Component 클래스에서 상속 한 반응 구성 요소와 함께 사용됩니다. – Ch4rAss

1

데코레이터를 사용하여 상속 받고 일부 믹스 인을 적용한 다음 새 클래스를 만들 수 있습니다. JS 클래스에는 다중 상속이 없으므로이 작업을 직접 수행 할 수는 없지만 두 작업을 수동으로 결합하거나 원하는 작업을 수행 할 프록시를 만들 수 있습니다.

I 클래스 like so 반환하여 decorator-based DI library에 대한 래퍼 클래스를 사용하고 :

static wrapClass(target, {hook = noop} = {}) { 
    return class wrapper extends target { 
    static get wrappedClass() { 
     return target; 
    } 

    constructor(...args) { 
     super(...Injector.fromParams(args).getDependencies(wrapper).concat(args)); 
    } 
    } 

}

데코레이터 정말 원래 동안 폐쇄와 함께 새로운 생성자를 반환을, 그러나 그것은을 위해 충분 대부분의 목적.

관련 문제