ES7 Decorators(修饰器)

ES6 Decorators(修饰器)

修饰器(Decorator)是一个函数,用来修改类的行为。这是ES7的一个提案,目前Babel转码器已经支持

我们在游戏大型项目种经常会用到的方法,现在es6直接支持

想要使用Decorator的话需要我们配置一下文件夹,配置一下环境

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

完事配置一下babelrc文件

"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(){

        } 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值