当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 详解es6超好用的语法糖Decorator

详解es6超好用的语法糖Decorator

2018年08月08日  | 移动技术网IT编程  | 我要评论
decorator(修饰器/装饰器)是es6提出的语法糖,用于修改类的行为。不过目前主流浏览器都没有很好的支持,我们需要用babel来转换为浏览器能识别的语言。在这篇文章中

decorator(修饰器/装饰器)是es6提出的语法糖,用于修改类的行为。不过目前主流浏览器都没有很好的支持,我们需要用babel来转换为浏览器能识别的语言。在这篇文章中将介绍decorator的基础用法和一些应用实例。

1.修饰类

(1) 基础用法

@testable
class myclass{}

function testable(target){
  target.istestable=true
}

console.log(myclass.istestable) // true

贴一下babel转换后的代码,

var _class;

let myclass = testable(_class = class myclass {}) || _class;

function testable(target) {
  target.istestable = true;
}

也可以在prototype上修改属性,也可以为修饰器添加多个参数。

@testable(false)
class myanotherclass{
  
}
function testable(status){
  return target=>{target.prototype.istestable=status}
}
console.log('myclass.istestable',myanotherclass.prototype.istestable) // false

当然我们通过修饰器,把某个对象的方法添加到目标类的实例上,注意要在类的prototype上添加。

const foo={istestable:true}
function testable(...list){
  return target=>{object.assign(target.prototype,...list)}
}

@testable(foo)
class myanotherclass{}
const obj=new myanotherclass()

console.log('myclass.istestable',obj.istestable) // true

(2) 应用

react app的开发中,使用redux通常需要react-redux中的connect方法,将两者结合在一起。通常的写法是:

class myreactcomponent extends react.component {}

export default connect(mapstatetoprops, mapdispatchtoprops)(myreactcomponent);

如果使用decorator,代码可读性更高了一些。

@connect(mapstatetoprops, mapdispatchtoprops)
export default class myreactcomponent extends react.component {}

2.修饰方法

(1).基础用法

// target:在方法中的target指向类的prototype
function readonly(target,key,descriptor){
  descriptor.writable=false
  return descriptor
}

class myclass{
  @readonly
  print(){console.log(`a:${this.a}`)}
}

(2).js中object的属性

var person = {}
object.defineproperty(person,'name',{
  configurable:false,//能否使用delete、能否需改属性特性、或能否修改访问器属性、,false为不可重新定义,默认值为true
  enumerable:false,//对象属性是否可通过for-in循环,flase为不可循环,默认值为true
  writable:false,//对象属性是否可修改,flase为不可修改,默认值为true
  value:'xiaoming' //对象属性的默认值,默认值为undefined
});

对应到descriptor为下面四个属性:

{
   value: specifiedfunction,
   enumerable: false,
   configurable: true,
   writable: true
};

(3). 应用

我们开始写一个@log修饰器,可以输出日志:

class math{
  @log
  add(a,b){
    return a+b
  }
}

const math=new math()
math.add(1,2)

function log(target,name,descriptor){
  const oldvalue=descriptor.value

  descriptor.value=function(){
    console.log(`calling ${name} with ${json.stringify(arguments)}`)
    return oldvalue.apply(this,arguments)
  }

  return descriptor
}

上面的代码中,@log作用是在返回结果前,打印函数名和其参数,起到输出日至的作用。上面的程序运行后,控制台将输出:

calling add with {"0":1,"1":2}

(4). 多个修饰器

良好命名的修饰器可以起到简洁注释的作用,如下:

class example {
  @readonly
  @enumable
  method(){}
}

多个修饰器的执行顺序是由外向内进入;再由内向外执行。

class example {
  @decorator(1)
  @decorator(2)
  method(){}
}

function decorator(id){
  console.log('id is ',id)
  return (target,property,descriptor)=>console.log('executed',id)
}

控制台输出

id is  1
id is  2
executed 2
executed 1

附录:babel配置

babel插件transform-decorators还没有正式版,我们可以用transform-decorators-legacy

安装babel

yarn add babel-plugin-transform-decorators-legacy babel-preset-es2017

配置.babelrc

{
  "presets": ["es2017"],
  "plugins":[
    "transform-decorators-legacy"
  ]
}

执行编译后的文件

因为我们为了测试,没必要非得放在浏览器里看了,可以用node执行babel转换后的文件。直接运行yarn start

// package.json

 "scripts": {
  "build": "babel ./decorator -d lib",
  "start":"yarn build && node ./lib/index.js"
 },

参考链接


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网