介绍
※ 为对象添加新功能
※ 不改变其原有的结构和功能
实现代码(ES6)
class Circle{
draw(){
console.log('换一个圆形')
}
}
class Decorator{
constructor(circle){
this.circle = circle;
}
draw(){ //在不影响老的功能情况下,添加新的功能
this.circle.draw();
this.setRedBorder(circle)
}
setRedBorder(circle){
console.log('设置红色边框')
}
}
let circle = new Circle()
circle.draw() //原本的画图
console.log('-----------------')
let dec = new Decorator(circle)
dec.draw() //装饰器处理之后的画图
使用场景
● ES7 装饰器
● core-decorators
设计原则
● 将现有对象和装饰器进行分离,两者独立存在
● 符合开放封闭原则
ES7中装饰器用法
@testDec
class Demo{
//...
}
function testDec(target){ //这里把Demo传进去
target.isDec = true //添加一个属性为true
}
console.log(Demo.isDec) //输出这个属性 true
@testDec(false) //传一个false
class Demo {
}
console.log(Demo.isDec) //输出false
function testDec(isDec){ //接收
return function(target){ //传入Demo类
target.isDec = isDec //赋值操作
}
}
Mixins
@mixins(Foo)
const Foo = {
foo(){
console.log('foo')
}
}
class MyClass {
}
function mixins(...list){
return function (target){
Object.assign(target.prototype,...list)
}
}
let obj = new MyClass()
obj.foo()
readonly
class Person {
constructor(){
this.first = 'A'
this.last = 'B'
}
@readonly
name() {
return `${this.first} ${this.last}`
}
}
function readonly(target,name,descriptor){
descriptor.writable = false //可读不可写
return descriptor
}
let p = new Person();
p.name() //正常
p.name = function(){ //报错。设置了只读
alert('aaa')
}
附上 core-decorators地址github.com/jayphelps/c…