你是否了解JavaScript中的元数据?

在 ES6 的规范当中,ES6 支持元编程,核心是因为提供了对 Proxy 和 Reflect 对象的支持,简单来说这个 API 的作用就是可以实现对变量操作的函数化,也就是反射。

元数据

什么是元数据

元数据是指附加在对象、类、方法、属性、参数上的数据,它可以用来帮助实现某种业务功能需要用到的数据。

元数据的使用

Reflect-metadata-ES7 的一个提案,它主要用来声明的时候添加和读取元数据,Typescript1.5+ 的版本已经支持它,你只需要:

npm i reflect-metadata --save

紧接着你要在 tsconfig.json 文件中添加以下配置:

{
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  }
}

defineMetadata() 和 getMetadata()

该方法是一个函数重载,它既可以接收三个参数,也可以是四个参数,具体定义如下所示:

function defineMetadata(metadataKey: any, metadataValue: any, target: Object): void;

function defineMetadata(metadataKey: any, metadataValue: any, target: Object, propertyKey: string | symbol): void;

它们的参数分别是:

  • metadataKey: 用于存储和检索元数据的键;
  • metadataValue: 元数据的值;
  • target: 要在其上定义元数据的目标对象;
  • propertyKey: 目标对象上的属性;

有存值的就有取值的,这个方法也是一个函数重载,它的具体定义如下所示:

function getMetadata(metadataKey: any, target: Object, propertyKey: string | symbol): any;

function getOwnMetadata(metadataKey: any, target: Object): any;

它的具体使用如下所示:

import "reflect-metadata";

const moment = { address: "广州" };

Reflect.defineMetadata("method", "hi,叼毛,你上班是不是在摸鱼", moment);
console.log(Reflect.getMetadata("method", moment)); // hi,叼毛,你上班是不是在摸鱼

Reflect.defineMetadata("method", "hi,靓仔,买菜吗", moment, moment.address);
console.log(Reflect.getMetadata("method", moment, moment.address)); // hi,靓仔,买菜吗

metadata()

Reflect.metadata(...) 方法的可以用于类或者类属性上,它的具体定义如下所示:

function metadata(
  metadataKey: any,
  metadataValue: any
): {
  (target: Function): void;
  (target: Object, propertyKey: string | symbol): void;
};

Reflect.metadata 当作 Decorator 使用,当修饰类时,在类上添加元数据,当修饰类属性时,在类原型的属性上添加元数据:

import "reflect-metadata";

@Reflect.metadata("inClass", "哇哈哈哈哈")
class Test {
  @Reflect.metadata("inMethod", "我要喝喜之郎,我要当太空人")
  public hello(): string {
    return "hello world";
  }
}

console.log(Reflect.getMetadata("inClass", Test)); // 哇哈哈哈哈
console.log(Reflect.getMetadata("inMethod", new Test(), "hello")); // 我要喝喜之郎,我要当太空人

在这里可能会有人就好奇了,这里面的方法怎么和上面的不一样啊,上面的是 defineMetadata(...),而这里直接用的 metadata(...),这是为什么呢?

答案是 defineMetadata(...) 它要确定你要是在哪里定义的元数据,而后者是直接以装饰器的方式调用,它已经明确知道了你就是给这个类来定义的元数据。

获取类型信息并赋值

我们可以通过 Reflect.getMetadata 方法来获取属性类型,并且对该属性进行赋值,如下操作所示:

import "reflect-metadata";

function Prop(): PropertyDecorator {
  return (target, key: string) => {
    const type = Reflect.getMetadata("design:type", target, key);
    console.log(`${key} type: ${type.name}`);
    target[key] = "moment";
  };
}

class SomeClass {
  @Prop()
  public nickname!: string;
}

console.log(new SomeClass().nickname); // moment

例如在 vue-property-decorator 中通过使用 Reflect.getMetadata API,Prop Decorator 能获取属性类型传至 Vue,简要代码如下:

import { Vue, Component, PropSync } from 'vue-property-decorator'

@Component
export default class YourComponent extends Vue {
  @PropSync('name', { type: String }) syncedName!: string
}

这样的写法就等同于以下代码所示:

export default {
  props: {
    name: {
      type: String,
    },
  },
  computed: {
    syncedName: {
      get() {
        return this.name
      },
      set(value) {
        this.$emit('update:name', value)
      },
    },
  },
}

除了能获取属性类型以外,通过 Reflect.getMetadata("design:paramtypes", target, key) 和 Reflect.getMetadata("design:returntype", target, key) 可以分别获取函数参数类型和返回值类型,具体代码如下所示:

import "reflect-metadata";

function Func(): PropertyDecorator {
  return (target, key: string) => {
    console.log(Reflect.getMetadata("design:paramtypes", target, key)); // 函数参数类型
    console.log(Reflect.getMetadata("design:returntype", target, key)); // 返回值类型
  };
}

class SomeClass {
  @Func()
  moment(value: boolean): string {
    return " ";
  }
}

自定义 metadataKey

除了能获取类型信息外,常用与自定义 metadataKey,并在合适的实际获取它的值,具体实例代码如下所示:

import "reflect-metadata";

function classDecorator(): ClassDecorator {
  return (target) => {
    Reflect.defineMetadata("class", "类装饰器", target);
  };
}

function methodDecorator(): MethodDecorator {
  return (target, key, descriptor) => {
    Reflect.defineMetadata("method", "方法装饰器", target, key);
  };
}

@classDecorator()
class SomeClass {
  @methodDecorator()
  someMethod() {}
}

console.log(Reflect.getMetadata("class", SomeClass)); // 类装饰器
console.log(Reflect.getMetadata("method", new SomeClass(), "someMethod")); // 方法装饰器

参考文献

总结

元数据的应用场景很多,其中 NestJs 就是使用了大量的元数组实现了控制反转和依赖注入,将会在下一篇文章中讲到,本篇文章到此结束。

原文链接:https://juejin.cn/post/7221559896214831162 作者:Moment

(0)
上一篇 2023年4月14日 上午10:16
下一篇 2023年4月14日 上午10:26

相关推荐

发表评论

登录后才能评论