介绍

  • 为对象添加新的功能
  • 不改变原有的结构和功能

(手机壳)

UML类图

点击查看【processon】

代码

  1. class Circle {
  2. draw() {
  3. console.log('画了个圆')
  4. }
  5. }
  6. class Decorator {
  7. constructor(circle) {
  8. this.circle = circle
  9. }
  10. draw() {
  11. this.circle.draw()
  12. this.setRedBorder(circle)
  13. }
  14. setRedBorder(circle) {
  15. console.log('设置了circle边框颜色为red')
  16. }
  17. }
  18. const circle = new Circle()
  19. circle.draw()
  20. const client = new Decorator(circle)
  21. client.draw()

场景

  • ES7 装饰器
    • core-decorators
    • 装饰器返回的是一个函数

以下:装饰类

  1. @test
  2. class Demo {
  3. }
  4. function test(target) {
  5. target.isDec = true
  6. }
  7. alert(Demo.isDec);
  1. function test(isDec) {
  2. return function(target) {
  3. target.isDec = isDec
  4. }
  5. }
  6. @test(false)
  7. class Demo {
  8. }
  9. alert(Demo.isDec);
  1. function mixins(...list) {
  2. return function(target) {
  3. Object.assign(target.prototype, ...list)
  4. }
  5. }
  6. const Foo = {
  7. show() {
  8. console.log('show')
  9. }
  10. }
  11. @mixins(Foo)
  12. class MyClass {}
  13. const m = new MyClass()
  14. m.show()

以下:装饰方法

  1. function readonly(target, name, descriptor) {
  2. descriptor.writable = false
  3. console.log(descriptor)
  4. return descriptor
  5. }
  6. class Person {
  7. constructor() {
  8. this.first = 'A'
  9. this.last = 'B'
  10. }
  11. @readonly
  12. name() {
  13. return `${this.first} ${this.last}`
  14. }
  15. }
  16. const p = new Person()
  17. console.log(p.name())
  18. // 错误
  19. p.name = function() {
  20. console.log(121)
  21. }
  22. console.log(p.name())
  1. function log(target, name,descriptor) {
  2. let oldVal = descriptor.value
  3. descriptor.value = function() {
  4. console.log(`此处为装饰器 打印 方法为${name}, 值为`, arguments)
  5. return oldVal.apply(this, arguments)
  6. }
  7. return descriptor
  8. }
  9. class Demo {
  10. @log
  11. add(a, b) {
  12. return a + b
  13. }
  14. }
  15. const d = new Demo()
  16. d.add(1,2)