es7的Decorators(裝飾器)

es7的Decorators(裝飾器)

修飾器(Decorator)是一個函數,用來修改類的行爲。這是ES7的一個提案,目前Babel轉碼器已經支持。
須要先安裝一個插件:npm install babel-plugin-transform-decorators-legacy --save-dev 而後在項目根目錄下,找到:.babelrc=>修改成"plugins": ["transform-decorators-legacy"]
//裝飾器本質是一個函數
//裝飾對象能夠使用多個裝飾器
//裝飾器能夠帶參數
//裝飾器修飾類,實例方法
//aop 設計思想(log,郵件發送)
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("作夢")
    study(){
        console.log(this.name+"在家睡覺"+this.ke);
    }
}
console.log(Student.schoolName);//打印師徒課堂.
console.log(Student.home);//打印黑龍江.

let l = new Student("姜姜");
l.study();//打印姜姜在家睡覺作夢.

@school
class Teacher {
    
}
console.log(Teacher.schoolName);//打印師徒課堂
咱們須要babel轉成es5,由於不少瀏覽器還不支持這麼高版本的代碼
相關文章
相關標籤/搜索