Home>

Development based on Class with JavaScript.
When the contents of Class increased, I thought of changing to another Class as shown below, but I thought that it would be strange to use several new in Class

Applicable source code
class d {
    ...
}
class a {
    constructor (bb) {
        this.bb = bb;
    }
    c (cc) {
        new d ();
    }
}

Use multiple classes or use simple functions

I didn't like both, so I'd like to know something good implementation.

Supplemental information (FW/tool version etc.)

node, ts

  • Answer # 1

    The expression

    new d ();is basically used to create a new object.
    Isn't it correct to keep an object created by new as a member?
    Or, if you doextends, usesuperto call the function of the inheritance class.

    Also, even if it is `` another class because the contents have increased '', there must be a basis for object-oriented design.
    Roughly speaking, there are relations that should beextends(A is B (one kind)) and relations that should be kept as members (A has B). > Which one is appropriate depends on the scene because there are some that are easy to understand whether it is inheritance or retention, such as `` car and car model '' `` car and tire '', others are not so.

    For example, even if the content of the class "user" increases and another class is created, the following rationale can be found:

    Since the things to be held differ depending on the "type" of the user, the common part is held in the user common class, it is extended for each type, and the inheritance source method is called using super in the inheritance destination.

    A lot of elements are packed, so classify the elements, create separate classes for each classification, and keep them in the user class.

    etc ... No matter what kind of decomposition, if there is a solid basis, there is no problem to new another element as a member.
    On the other hand, if you want to renew randomly, you should review your design.

Related articles