装饰器(Decorator)是—个函数,用来修改类的行为。装饰器对类的行为的改变, 是编译时发生的,而不是在运行时。
作用:是—种动态地往—个类中添加新的 行为的设计模式, 它可以在类运行时,扩展—个类的功能,并且去修改类本身的属性和方法,使其可以在不同类之间更灵活的共用—些属性和方法。
//装饰器本庚就是编译时执行的函数 @decorator class A{} //等同于 class A{} A = decorator(A) || A;
装饰类
//@testable就是—个装饰器。 它修改了MyClass这个类的行为,为它加上了静态属性 inTestable。 //装饰器函数的第—个参数target, 就是需要装饰的目标类。 function testable(target){ target.inTestable = true; } @testable class MyClass{} console.log(MyClass.inTestable); // true
//通过装饰器mixins, 把Foo类的方法添加到了MyClass的实例上面 // mixins.js export function mixins(…list) { return function (target) { Object.assign(target.prototype, …list) } } //main.js import { mixins } from'./mixins' const Foo = { foo(){ console. log('foo'); } } @mixins(Foo) class MyClass{} let obj = new MyClass(); obj.foo();
装饰类的属性\方法
类似Object.defineprototype()方法。它接收三个参数target, name , descriptor。 第—个target是所要装饰的目标对象,第二个name是所要装饰的属性名,第三个descriptor是该属性的描述对象。 Decorator在babel的情况下对成员属性的动态修改实际上是通过defineProperty实 现的。如果被装饰的成员是函数,则第三个参数的value字段表示这个函数本身。
//日志输出装饰器 function log(target,name,descriptor){ console.log(Date.now()); } class Car { @log run(){ console.log{'Car is running'); } } const c1 = new Car(); c1.run(); //64 //Car is running
//属性只读装饰器 class Person { @readonly name() { return `${this.first} ${this.last}` } } function readonly(target, name, descriptor) { //descriptor对象原来的借如下 //{ // value: speci什edFunction, II enumerable: false, // configurable: true, // writable: true //}; descriptor.writable = false; return descriptor; }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/233557.html原文链接:https://javaforall.net