我有一個包含fromJson方法的對象。此方法不起作用,因爲該類的私有屬性無法訪問?什麼是錯誤的以及如何處理它?代碼是用TypeScript編寫的。Typescript:使用fromJson方法指定的對象,如何測試私有屬性是否存在並設置它
class Example {
private Foo: string; // does not matter if private or public, same effect, and normaly has to be private
constructor(input?: string) {
if (!!input) {
this.foo = input;
}
}
set foo(value: string) {
this.Foo = value;
}
get foo(): string {
return this.Foo;
}
public static fromJson(obj: Object) {
let result: Example = new Example();
for (let index in obj) {
if (Example.hasOwnProperty(index)) { // never runs because false
result[index] = obj[index];
}
/* allready tried this -> same result */
// if (result.hasOwnProperty(index)) {
// result[index] = obj[index];
//}
// let descriptor = Object.getOwnPropertyDescriptor(Example, index); // = undefined
// let descriptor = Object.getOwnPropertyDescriptor(result, index); // = undefined
}
return result;
}
public toJsonString() {
return JSON.stringify(this);
}
public toJsonObject() {
return JSON.parse(this.toJsonString());
}
}
let a = new Example('one');
let json = a.toJsonObject(); // this looks exactly like my api response (type json)
let obj = Example.fromJson(json);
console.log(json);
console.log(obj);
但console.log(obj)
必須<Example> {"Foo": "one", foo(...)}
編輯:生成的JavaScript:
var Example = (function() {
function Example(input) {
if (!!input) {
this.foo = input;
}
}
Object.defineProperty(Example.prototype, "foo", {
get: function() {
return this.Foo;
},
set: function (value) {
this.Foo = value;
},
enumerable: true,
configurable: true
});
Example.fromJson = function (obj) {
var result = new Example();
for (var index in obj) {
if (Example.hasOwnProperty(index)) {
result[index] = obj[index];
}
}
return result;
};
Example.prototype.toJsonString = function() {
return JSON.stringify(this);
};
Example.prototype.toJsonObject = function() {
return JSON.parse(this.toJsonString());
};
return Example;
}());
var a = new Example('one');
var json = a.toJsonObject(); // this looks exactly like my api response (type json)
var obj = Example.fromJson(json);
console.log(json);
console.log(obj);
生成的JavaScript看起來像什麼? – Arg0n
@ Arg0n通過編輯提出問題 – TypedSource
如果爲'Foo'賦值,生成的JS會發生什麼? '私人Foo:string = null;' – Arg0n