EdwardZZZ / articles

工作点滴记录
2 stars 0 forks source link

用decorater实现私有属性代替immutable怎么样? #1

Open EdwardZZZ opened 7 years ago

EdwardZZZ commented 7 years ago

用decorator创建私有属性,再用decorator去操作私有属性,完全抛弃immutable这个想法怎么样?

我想做的就是用decorator实现去代替immutable,这样不用学习新的api,使用也更简单。

EdwardZZZ commented 5 years ago

function f() {
    console.log("f(): evaluated");
    return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
        console.log("f(): called");

        const { value, configurable, enumerable } = descriptor;
        return {
            configurable,
            enumerable,
            writable: true,
            value: async function before(...props: any[]) {
                console.log(1);
                return value.apply(this, props);
            },
        };
    }
}

function g() {
    console.log("g(): evaluated");
    return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
        console.log("g(): called");

        const { value, configurable, enumerable } = descriptor;
        return {
            configurable,
            enumerable,
            writable: true,
            value: async function before(...props: any[]) {
                console.log(2);
                return value.apply(this, props);
            },
        };
    }
}

class C {
    @f()
    @g()
    method() {
        console.log(123);
    }
}

const c = new C();
c.method();