5

Decorator(装饰器,修饰器,实例方法)

Decorator:

function school(target){
        target.schoolName="师徒课堂";
    }
        function hometown(diqu){
            return function(target){
                target.home=diqu;
            }
        }
        function studyke(kemu){
            return function(target){
                target.ke=kemu;
            }
        }
    
        @hometown("广灵县")
        @school
            
        class Student {
            constructor(name){
                this.name=name;
            }
            @studyke("jquery")
            study(){
                console.log(this.name+"在学习"+this.ke);
            }
        }
        console.log(Student.schoolName);//打印师徒课堂.
        console.log(Student.home);//打印广灵县.
            
        let l = new Student("宋泽");
        l.study();//打印宋泽在学习jquery.
            
        @school
        class Teacher {
            
        }
        console.log(Teacher.schoolName);//打印师徒课堂.

  • 注释:

        1.装饰器本质是一个函数;
        2.装饰对象可以使用多个装饰器;
        3.装饰器可以带参数;
        4.装饰器修饰类,实例方法;
        5.aop 设计思想(log,邮件发送)。

songze
211 声望13 粉丝

该来的总会来,该走的不挽留!