2017-12-14 4 views
1

부모 클래스에서 자식 메서드를 호출하는 것이 좋고/나쁜 방법입니까?ES6의 부모 클래스에서 자식 메서드 호출

class Parent { 
    constructor() { 
     // if 'autoPlay' exists (was implemented) in chain 
     if (this.autoPlay) { 
      this.autoPlay(); // execute from parent 
     } 
    } 
} 

class ChildA extends Parent { 
    autoPlay() { 
     console.log('Child'); 
    } 
} 

class ChildB extends Parent { 
    // 'autoPlay' wasn't implemented 
} 

const childA = new ChildA(); 
const childB = new ChildB(); 
+0

예, 상위 클래스는 하위 클래스와 계약이 없으며, 다른 방법입니다. 게다가 이해할 수 없을 것입니다. 그냥 부모 클래스에 메소드를 옮기십시오. –

+0

@LucasSteffen, 'Parent'를 확장하는 모든 클래스에는 자체 'autoPlay'구현이 있습니다. 따라서 그 방법을 부모 클래스로 옮기는 것은 불가능합니다. –

+0

@AliMamedov 모든 어린이가 정의해야합니까? 이 경우 부모에 구현해야하지만 오류가 발생합니다. 'autoPlay() {뭔가 새로운 오류 던져 ('autoPlay 구현해야합니다'); }'. – Paulpro

답변

2

인가?

예, 완전히 정상적인 관행입니다. 부모 클래스는 인스턴스의 일부 메서드를 호출하고 자식 클래스가 메서드를 재정의 한 경우 자식 메서드가 호출됩니다. 그러나 대개는 "내 인스턴스가이 메서드를 정의 했습니까?"테스트를 수행하지 않을 것입니다. 호출하면됩니다. 기본적으로 아무것도하지 않으려면 @ scipers의 대답과 같이 빈 메소드를 정의하면됩니다. 메서드를 추상화 (자식 클래스를 강제로 재정의하도록)하려면 정의되지 않은 상태로 두거나 적절한 예외를 throw하는 메서드를 정의 할 수 있습니다.

가 부모 생성자에서 아이 메소드를 호출하는 나쁜 관행은 무엇입니까?

Yes. Don't do that.은 (는 모든 언어의 문제입니다).

생성자의 목적은 인스턴스를 초기화하는 것입니다. 부작용의 호출을 발신자에게 맡깁니다. 이렇게하면 모든 하위 생성자가 초기화 작업을 완료하도록 할 수 있습니다.

인위적인 예 : Parent 생성자 autoplay를 호출 않은 경우 문제가 해결되지 얼마나

class Parent { 
    autoPlay() { 
     this.play("automatically "); // call child method 
    } 
    play(x) { 
     console.log(x+"playing default from "+this.constructor.name); 
    } 
} 

class ChildA extends Parent { 
    // does not override play 
} 
class ChildB extends Parent { 
    constructor(song) { 
     super(); 
     this.song = this; 
    } 
    play(x) { 
     console.log(x+"playing "+this.song+" from ChildB"); 
    } 
} 

const child1 = new ChildA(); 
child1.autoPlay(); 
const child2 = new ChildB("'Yeah'"); 
child2.autoPlay(); 

알 수 있습니다. 인스턴스 생성 후 어디에서나 추가 메서드 호출이 필요하지 않은 경우 도우미 함수를 사용하십시오. 그것은 심지어 정적 메소드 일 수도 있습니다 :

class Parent { 
    autoPlay() { … } 
    play { … } 
    static createAndAutoPlay(...args) { 
     const instance = new this(...args); 
     instance.autoPlay(); 
     return instance; 
    } 
} 
… 
const child1 = ChildA.createAndAutoPlay(); 
const child2 = ChildB.createAndAutoPlay("'Yeah'"); 
4

Parent 클래스에서 autoPlay의 빈 구현을 정의하고 하위 클래스에서이를 재정의하는 것이 더 좋을 수 있습니다. 그것은 부모 클래스에서 자식 메소드를 호출하는 것이 좋습니다

class Parent { 
    constructor() { 
    this.autoPlay(); 
    } 

    autoPlay() { 

    } 
} 

class Child extends Parent { 
    autoPlay() { 
    console.log('Child'); 
    } 
} 

const child = new Child(); 
+0

왜 이것이 다운 voted인지 확실하지 않습니다. – Bergi

+0

왜 이것이 다운 voted인지 확실하지 않습니다. – Paulpro

+0

글쎄, 그건 여전히 나쁜 습관이야. 아마 그게 이유 야. – scipper