ES7 Decorators(修饰器)

发布时间:2019-08-19 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了ES7 Decorators(修饰器)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

ES6 Decorators(修饰器)

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

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

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

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

完事配置一下babelrc文件

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

先说一下装饰器的特点

  • 装饰器本质是一个函数
@H_126_67@@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(){

        } 

脚本宝典总结

以上是脚本宝典为你收集整理的ES7 Decorators(修饰器)全部内容,希望文章能够帮你解决ES7 Decorators(修饰器)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。