ES7 Decorators(修飾器)

ES6 Decorators(修飾器)

修飾器(Decorator)是一個函數,用來修改類的行爲。這是ES7的一個提案,目前Babel轉碼器已經支持es6

咱們在遊戲大型項目種常常會用到的方法,如今es6直接支持

想要使用Decorator的話須要咱們配置一下文件夾,配置一下環境npm

npm install babel-plugin-transform-decorators-legacy --save-dev

完事配置一下babelrc文件babel

"plugins": ["transform-decorators-legacy"]

先說一下裝飾器的特色函數

  • 裝飾器本質是一個函數
@hometown     hometown()
  • 裝飾對象可使用多個裝飾器
@hometown("山西")
@school
    class Student{
        constructor(name){
            this.name=name;
        }
        @studyke("HTML")
        study(){
            console.log(this.name+"  is studying"+this.ke+"!")
        }
}
  • 裝飾器能夠帶參數
function hometown(diqu){
            //target.home="xx";
            return function(target){
               target.home=diqu;
            }
        }

@hometown("山西")
class...
  • 裝飾器修飾 類
function school(target){
            console.log("123")
            target.schoolName="xxxx";
        }
        function hometown(diqu){
            //target.home="xx";
            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("HTML")
            study(){
                console.log(this.name+"  is studying"+this.ke+"!")
            }
        }
        console.log(Student.schoolName);
        console.log(Student.home);

        let l=new Student("xiaoA");
        l.study();

        @school
        function Teacher(){

        }
相關文章
相關標籤/搜索