0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Mixin の極めてシンプルな例

Posted at

元になるクラスの宣言

まず、Mixin をする 2 つのクラス ClassA, ClassB を作成する。
更に、継承元の BaseClass を作成する。

prepare.ts
class ClassA {
    methodA() { console.log('method A'); }
}

class ClassB {
    methodB() { console.log('method B'); }
}


class BaseClass {
    member="member"
}

Mixin の定義

はじめに、コンストラクタ型を一般的に定義しておく。
次に、作成したいクラス MixinAB のコンストラクタを function として定義する。
このとき、 methodA, methodB の実装は ClassAClassB に委譲する。
このままだと、常に new MixinAB(BaseClass) として呼び出す必要があり、MixinAB の利用先から BaseClass への非本質的な依存関係が生じる。
これを防ぐために、MixinAB を継承する形で MergedClass を定義する。

Mixn.ts
type Constructor<T = {}> = new (...args: any[]) => T;

function MixinAB<B extends Constructor>(Base: B) {
    return class extends Base {
        methodA = new ClassA().methodA;
        methodB = new ClassB().methodB;
    };
}

class MergedClass extends MixinAB(BaseClass) {}

Mixin の使用

use.ts
const merged = new MergedClass();
merged.methodA(); // method A
merged.methodB(); // method B
console.log(merged.member); // member
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?