How to properly wrap constructors with decorators in TypeScript

后端 未结 5 1999
猫巷女王i
猫巷女王i 2020-12-28 08:32

The process of wrapping a class with a decorator causes superclasses to be unable to access that classes\' properties. Why?

I have some code that:

  1. Crea
5条回答
  •  猫巷女王i
    2020-12-28 09:08

    If you like run code after and before constructor() with a decorator:

    function ClassWrapper() {
        return function(target: any) {
            // save a reference to the original constructor
            var original = target;
    
            // the new constructor behaviour
            var f: any = function (...args) {
                console.log('ClassWrapper: before class constructor', original.name);
                let instance = original.apply(this, args)
                console.log('ClassWrapper: after class constructor', original.name);
                return instance;
            }
    
            // copy prototype so intanceof operator still works
            f.prototype = original.prototype;
    
            // return new constructor (will override original)
            return f;
        };
    }
    @ClassWrapper()
    export class ClassExample {
        public constructor() {
            console.info('Running ClassExample constructor...');
        }
    }
    
    let example = new ClassExample();
    
    /*
    CONSOLE OUTPUT:
    ClassWrapper: before class constructor ClassExample
    Running ClassExample constructor...
    ClassWrapper: after class constructor ClassExample
    */
    

提交回复
热议问题