【发布时间】:2020-05-25 22:19:22
【问题描述】:
我是 JavaScript 新手,如果我要问的不是“你如何在 JavaScript 中做到这一点”,请耐心等待。欢迎提供其他方法的建议。
我有一个名为State 的类,我需要使用JSON.stringify() 序列化该类的对象。下一步是将它们反序列化回对象。但是,我的班级使用 setter 和 getter。
我面临的问题是,在我反序列化这些对象后,setter 和 getter 似乎消失了。我只是不知道如何正确地将序列化对象转换回该类的对象,以便它们的行为与直接使用 new 创建的对象完全相同。
在另一种语言中,我会将这些对象转换为 State 对象。我找不到似乎以这种方式工作的 JavaScript 机制。
代码如下:
class State {
constructor(href) {
this.url = href;
}
set url(href) {
this._url = new URL(href);
this.demoParam = this._url.searchParams.get("demoParam");
}
get url() {
return this._url;
}
set demoParam(value) {
let param = parseInt(value, 10);
if(isNaN(param)) {
param = 2;
}
console.log("Setting 'demoParam' to value " + param);
this._demoParam = param;
}
get demoParam() {
return this._demoParam;
}
toJSON() {
let stateObject = {};
const prototypes = Object.getPrototypeOf(this);
for(const key of Object.getOwnPropertyNames(prototypes)) {
const descriptor = Object.getOwnPropertyDescriptor(prototypes, key);
if(descriptor && typeof descriptor.get === 'function') {
stateObject[key] = this[key];
}
}
return stateObject;
}
}
let originalState = new State(window.location.href);
let newState1 = JSON.parse(JSON.stringify(originalState));
newState1.demoParam = 12;
let newState2 = Object.create(State.prototype, Object.getOwnPropertyDescriptors(JSON.parse(JSON.stringify(originalState))));
newState2.demoParam = 13;
let newState3 = Object.assign(new State(window.location.href), JSON.parse(JSON.stringify(originalState)));
newState3.demoParam = 14;
let newState4 = Object.setPrototypeOf(JSON.parse(JSON.stringify(originalState)), State.prototype);
newState4.demoParam = 15;
我希望每次设置newStateX 对象的demoParam 属性时都会看到控制台日志消息。然而。我只看到两次,即每个 new State(window.location.href) 语句。
我使用了this问题的答案。但是,它并没有按预期工作。
【问题讨论】:
标签: javascript stringify ecmascript-2017