【发布时间】:2016-10-09 18:36:38
【问题描述】:
当我发现 Typescript 的私有根本不是私有的,并且 get set 属性没有通过 JSON.stringify 输出时,我需要在 angular 2.0.0-rc1 中将一个对象序列化为 json。
于是我开始装饰班级:
//method decorator
function enumerable(value: boolean) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
descriptor.enumerable = value;
};
}
//property decorator
function exclude(target: any, propertyKey: string): any {
return { enumerable: false };
}
class MyClass {
test: string = "test";
@exclude
testExclude: string = "should be excluded";
@enumerable(true)
get enumerated(): string {
return "yes";
}
@enumerable(false)
get nonEnumerated(): string {
return "non enumerable"
}
}
let x = new MyClass();
//1st
console.log(JSON.stringify(x));
//2nd
console.log(JSON.stringify(x, Object.keys(MyClass.prototype)));
//3rd
console.log(JSON.stringify(x, Object.keys(x).concat(Object.keys(MyClass.prototype))));//test 3
{"test":"test"}
{"enumerated":"yes"}
{"test":"test","enumerated":"yes"}
但在我的项目(角度 2.0.0-rc1)中,这给出了
{"test":"test","testExclude":"should be excluded"}
{"enumerated":"yes"}
{"test":"test","testExclude":"should be excluded","enumerated":"yes"}
我真正想要的是游乐场的输出#3。
查看转译后的代码后, 唯一的区别是反射元数据的代码:
//snip ...
__decorate([
exclude,
__metadata('design:type', String)
], MyClass.prototype, "testExclude", void 0);
__decorate([
enumerable(true),
__metadata('design:type', String)
], MyClass.prototype, "enumerated", null);
__decorate([
enumerable(false),
__metadata('design:type', String)
], MyClass.prototype, "nonEnumerated", null);
return MyClass;
}());
操场上没有__metadata 行。
这里发生了什么?我怎样才能在我的项目中获得 Playground 的第三名?
【问题讨论】:
标签: angularjs json angular-decorator reflect-metadata