类的装饰器总结

152 阅读1分钟

装饰器需要webpack的环境支撑,单纯的浏览器跟node跑不起代码

类的装饰器作用?

在执行类之前可以对类进行包装,只能修饰类,类中的属性,有类中的方法

特点一:装饰器必须是一个函数。

    @type
    class Animal{}
    function type(constructor){
        console.log(constructor);
        constructor.type = "哺乳类";
    }
    //上面的代码等价于type(Animal),可以理解为Animal通过形参constructor传入type方法中进行扩展

特点二:装饰器是可以存在多个的。

    @type1
    @type2
    class Animal{}
    function type1(){
        console.log(1);
    }
    function type2(){
        console.log(2);
    }
    //此时执行的打印顺序是2,1可以理解为就近执行。

特点三:装饰器是可以传参的。

    @type1("哺乳类")
    @type2("爬行类")
    class Animal{}
    //如何传参呢?首先装饰器必须是一个函数,所以type("哺乳类")执行完毕必须是一个函数。那我们就可以得到如下代码
    function type1(type){
        console.log(1);
        return function(constructor){
            console.log(2);
            constructor.type1 = type;
        }
    }
    function type2(type){
        console.log(3);
        return function(constructor){
            console.log(4);
            constructor.type2 = type;
        }
    }
    //此时的执行顺序是一个洋葱模型执行的打印结果为1,3,4,2。可以理解为,首先是type1跟type2的函数执行。函数执行时从上而下的,所是1,3。然后开始装饰类,类的装饰是就近原则,那么就是4,2。所以执行顺序为1-3-4-2。

小扩展。装饰器为什么不能修饰函数?

    @type
    function a(){
        
    }
    function type(constructor){
        console.log(constructor);
    }
    //原因跟简单,因为函数存在变量提升。上面的代码执行的时候直接变成了下面的代码。所以,装饰器不能装饰函数
    function a(){
        
    }
    @type