Decorator

装饰器

装饰器语法:

type Decorator = (value: Input//被装饰的值,在属性被装饰时为undefined。
, context: {
  kind: string;//装饰类型,可能取值为class,method,getter,field,accessor
  name: string | symbol;//被装饰的值名称
  access: {
    get?(): unknown;//取值器
    set?(value: unknown): void;//存值器
  };
  private?: boolean;//私有方法
  static?: boolean;//静态方法
  addInitializer?(initializer: () => void): void;//允许增加初始化逻辑
}) => Output | void;

装饰器可以装饰整个类:

@testable
class MyTestableClass {
  // ...
}

function testable(target) {
  target.isTestable = true;
}

MyTestableClass.isTestable // true

觉得一个参数不够用时可以再封装一层函数:

function testable(isTestable) {
  return function(target) {
    target.isTestable = isTestable;
    //如果是想在实例对象中添加属性的话,可以使用prototype来操作!
  }
}
@testable(true)
class MyTestableClass {}
MyTestableClass.isTestable // true
@testable(false)
class MyClass {}
MyClass.isTestable // false

Object.assign()的作用:将所有的可枚举的(Object.propertyIsEnumerable()为true即可以通过for...in...进行循环枚举,不可以是原型链继承的属性),自有的(Object.hasOwnProperty()返回为true)属性从一个或多个源对象复制到目标对象,比如:

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget === target);
// expected output: true
posted @ 2022-10-15 23:12  梦呓qwq  阅读(17)  评论(0编辑  收藏  举报