JavaScript设计模式之装饰器模式

原文博客地址:https://finget.github.io/2018/11/22/decorator/

装饰器模式

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

手机壳就是装饰器,没有它手机也能正常使用,原有的功能不变,手机壳可以减轻手机滑落的损耗。

代码示例

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()

let decorator = new Decorator(cicle)
decorator.draw()

ES7装饰器

// 简单的装饰器
@testDec // 装饰器
class Demo {}

function testDec(target){
  target.isDec = true
}
console.log(Demo.isDec) // true
// 装饰器原理
@decorator
class A {}

// 等同于
class A {}
A = decorator(A) || A; // 把A 作为参数,返回运行的结果
// 传参数
function testDec(isDec) {
  return function(target) { // 这里要 return 一个函数
    target.isDec = isDec;
  }
}
@testDec(true)
class Demo {
  // ...
}
alert(Demo.isDec) // true
装饰类
function mixins(...list) {
  return function (target) {
    Object.assign(target.prototype, ...list)
  }
}
const Foo = {
  foo() {
    console.log('foo')
  }
}
@mixins(Foo)
class MyClass{}

let myclass = new MyClass()
myclass.foo() // 'foo'
装饰方法
// 例1 只读
function readonly(target, name, descriptor){
  // descriptor对象原来的值如下
  // {
  //   value: specifiedFunction,
  //   enumerable: false, // 可枚举
  //   configurable: true, // 可配置
  //   writable: true // 可写
  // };
  descriptor.writable = false;
  return descriptor;
}

class Person {
  constructor() {
    this.first = 'A'
    this.last = 'B'
  }

  @readonly
  name() { return `${this.first} ${this.last}` }
}

var p = new Person()
console.log(p.name())
p.name = function () {} // 这里会报错,因为 name 是只读属性
// 例2 打印日志
function log(target, name, descriptor) {
  var oldValue = descriptor.value;

  descriptor.value = function() {
    // 1. 先打印日子
    console.log(`Calling ${name} with`, arguments);
    // 2. 执行原来的代码,并返回
    return oldValue.apply(this, arguments);
  };

  return descriptor;
}

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

const math = new Math();
const result = math.add(2, 4);
console.log('result', result);

成熟的装饰器库

最后

创建了一个前端学习交流群,感兴趣的朋友,一起来嗨呀!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值