ReactMasters / study

스터디 기록
1 stars 0 forks source link

11월 3주차 Mixin #33

Open 56aiden90 opened 2 years ago

56aiden90 commented 2 years ago

mixin #typescript #javascript

What are mixins?

Mixins are compartmentalized classes or functions that are used as a base component in order to assemble a more complex component or such programming design pattern.

Inheritance vs Mixins

Inheritance in OOP is similar to mixins in the sense that inheritance is also used to create a more complex class(child class) from a parent class.

class Tall {
    getCriteria() { "height > 180" }
}

class Heavy {
    getCriteria() { "weight > 90" }
}

// I want to make Giant class that is tall and heavy
// However, you cannot inherit multiple parent classes.

// class Giant extends Tall extends Heavy{

// }

class Person {

}

const Meh: { constructor: (...args: any[]) => any } = {
    constructor: () => {

    }
}

// const Me: Constructor = function(){

// }

// const me = new Me();

class ParentClass {
    public getCriteria?() {

    }
}

type Constructor = new (...args: any[]) => ParentClass;

type Constructor = new (...args: any[]) => any;

// TallMixin

// function TallMixin<SuperClass>(superClass: SuperClass) { // This will throw an compile error
function TallMixin<SuperClass extends Constructor>(superClass: SuperClass) {
    return class extends superClass {
        getCriteria = () => {
            if (super.getCriteria instanceof Function) {
                super.getCriteria();
            }
            console.log("height > 180cm");
        }
    }
}

function HeavyMixin<SuperClass extends Constructor>(superClass: SuperClass) {
    return class extends superClass {
        getCriteria = () => {
            if (super.getCriteria instanceof Function) {
                super.getCriteria();
            }
            console.log("weight > 90kg");
        }
    }
}

function addMixins<Constructor>(subClass: Constructor, ...mixins: any[]) {
    return mixins.reduce((prev, cur) => cur(prev), subClass);
}

const MixInApplication = HeavyMixin(TallMixin(Person));

//const MixinApplication2 = addMixins(Person, TallMixin, HeavyMixin);

const mixInApplicationInstance = new MixInApplication();

//const mixInApplicationInstance2 = new MixinApplication2();

mixInApplicationInstance.getCriteria();
mixInApplicationInstance2.getCriteria();

Resources https://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes/