我正在制作一个编辑器,它将查看 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/