所以如果我寫一個類如下
class Rectangle {
#width;
#height;
constructor() {
this.#width = 3;
this.#height = 5;
}
}
let rect = new Rectangle();
console.log(JSON.stringify(rect)); // returns {}
它將回傳一個空物件,完全忽略我所有的私有成員。添加 toJSON 方法有效,但這變得非常麻煩。是否有任何內置方法可以輕松地讓我的私有欄位顯示在 JSON.stringify 中?還是我只需要將每個成員都寫入 toJSON 方法中?
uj5u.com熱心網友回復:
私有屬性只能在類宣告本身內部訪問。您需要撰寫自己的序列化方法:
class Rectangle {
#width;
#height;
constructor() {
this.#width = 3;
this.#height = 5;
}
stringify() {
return JSON.stringify({['#width']: this.#width,['#height']: this.#height})
}
}
let rect = new Rectangle();
console.log(rect.stringify())
uj5u.com熱心網友回復:
避免必須寫出所有成員的一種選擇是在實體上有一個私有資料屬性,然后序列化/反序列化該屬性:
class Rectangle {
#data;
constructor(data) {
this.#data = data;
}
getWidth = () => this.#data.width;
toJson = () => JSON.stringify(this.#data);
}
const r = new Rectangle({ width: 1, height: 1 });
console.log(r.getWidth());
const stringified = r.toJson();
console.log(stringified);
const restructured = new Rectangle(JSON.parse(stringified));
console.log(restructured.getWidth());
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/348702.html
標籤:javascript json 班级 私人的
