当我发现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
在Typescript 操场上,这给出了
{"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。
看了一下转译后的代码,唯一的区别是 reflect-metadata 的代码:
//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 的#3 结果?