javascript - 设置有关属性的信息

标签 javascript typescript ecmascript-6

我正在制作一个编辑器,它将查看 javascript 类 (es6),并显示有关关键属性的特定信息。我想尝试使用装饰器来完成此任务,所以像这样:

class Transform extends Component {

    @serializable
    public position: Vector3 = Vector3.zero;

}

然后我的装饰器看起来像这样:

function serializable(...args): any {
    let target = args[0];
    let key = args[1];
    let descriptor = args[2] || {};
    descriptor.writable = true;
    descriptor.serializable = true;
    return descriptor;
}

然后,当我分析类(class)时,我会做这样的事情:

components.forEach(comp => {
    var info = Object.getOwnPropertyDescriptor(comp, 'position');
    if(info.serializable){
        // display in editor
    }
});

我遇到的问题是它可以让我设置额外的描述符值,但我无法访问它们。

我可以做什么来实现这个目标?

最佳答案

我不得不承认,这不是很清楚from the documentation ,因为它指出:

NOTE  A Property Descriptor is not provided as an argument to a property decorator due to how property decorators are initialized in TypeScript. This is because there is currently no mechanism to describe an instance property when defining members of a prototype, and no way to observe or modify the initializer for a property. As such, a property decorator can only be used to observe that a property of a specific name has been declared for a class.

但是然后:

If the property decorator returns a value, it will be used as the Property Descriptor for the member

所以我的理解是,虽然该函数无法更改描述符,但它可以通过像您一样返回描述符来“更改它”。
但我想事实并非如此,因为它不起作用。

但是,在其下方给出了如何使用 reflect-metadata 执行此操作的示例。 :

import "reflect-metadata";

const serializableMetadataKey = "serializable";

function serializable(): any {
    return Reflect.metadata(serializableMetadataKey, true);
}

function isSerializable(target: any, propertyKey: string) {
    return Reflect.getMetadata(serializableMetadataKey, target, propertyKey);
}

class Transform extends Component {
    @serializable()
    public position: Vector3 = Vector3.zero;
}

components.forEach(comp => {
    if (isSerializable(comp, "position")) {
        // display in editor
    }
});

关于javascript - 设置有关属性的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38881951/

相关文章:

javascript - 仅允许 td 中的数字,其中 contenteditable = true

javascript - Typescript:命名属性类型必须可分配给字符串索引器类型

Angular2 导入绝对路径或自定义路径(typescript 2)

javascript - 将 Javascript 可迭代对象转换为数组

javascript - 如何对对象数组进行排序

javascript - 新成员(member)注册时自动生成 HTML 页面

angular - 如何从 Visual Studio 2015 中的非相对路径导入模块

reactjs - 如何使用函数组件指定构造函数(粗箭头语法)?

javascript - 滚动时如何停止页脚前面的 block ?

angular - Firestore 从 Angular ​​获取单个数据