js 装饰器

89 阅读1分钟

什么是js装饰器?

  • 装饰器的本质就是一个函数
  • 为什么要使用装饰器?装饰器可以在不改变原有代码结构的情况下,对原有的功能进行扩展。
function create(target) {
  target.prototype.gun = 'AK'
}

//创建一个士兵类,这时候的士兵一无所有,就像现在的我一样,哈哈哈
class Solider {
  
}

//使用装饰器
@create
class Solider {}

//此时
console.log(new Solider().gun) //AK
  • 装饰器传递参数
function create(params: any, type: any) {
  return (target: any, attribute: any) => {
    target.prototype[type] = params;
  };
}

@create("b", "name")
@create(18, "age")
export default class Person {}

//外部使用时
const p1 = new Person()
console.log(p1.name) //b
console.log(p1.age) //18
  • 使用场景 image.png