欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

es7学习教程之Decorators(修饰器)详解

时间:2021-02-11 11:21:19|栏目:JavaScript代码|点击:

本文主要给大家介绍的是关于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="广灵";
   return function(target){
    target.home=diqu;
   }
  }

@hometown("山西")
class...

装饰器修饰 类

function school(target){
   console.log("123")
   target.schoolName="师徒课堂";
  }
  function hometown(diqu){
   //target.home="广灵";
   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(){

  } 

总结

上一篇:JavaScript鼠标悬停事件用法解析

栏    目:JavaScript代码

下一篇:微信小程序自定义tabBar在uni-app的适配详解

本文标题:es7学习教程之Decorators(修饰器)详解

本文地址:http://www.codeinn.net/misctech/61074.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有